﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.IO.Ports;

namespace iPower
{
    public partial class iPowerMain : Form
    {
        // Instance Variables
        /* Dynamic Button Objects - Realtime/Historic Sites & Meters */
        DynamicButtons cmdRealtimeSites = new DynamicButtons();
        DynamicButtons cmdRealtimeMeters = new DynamicButtons();
        DynamicButtons cmdHistoricSites = new DynamicButtons();
        DynamicButtons cmdHistoricMeters = new DynamicButtons();
        
        // Form Method Constructor
        public iPowerMain()
        {
            InitializeComponent();            

            //create Data Type for drop Down Boxes
            createDataTypes();

            // Raise a Event Handler to create Sites on Startup - very smart :)!!
            tabControlMain_Click(tabControlMain, EventArgs.Empty);

            // Raise a Event Handler to create default Selection for Historic Graph 
            //tabControlHistoric_Click(tabControlHistoric, EventArgs.Empty);

            // Create zedGraph - iPower.cs
            assignGraphControls();
        }

        // DataType Listbox creation
        public void createDataTypes()
        {
            List<String> listDataTypes = new List<String>();

            listDataTypes.Add("INT");
            listDataTypes.Add("LONG");
            listDataTypes.Add("INT/SCALE");
            listDataTypes.Add("LONG/SCALE");
            listDataTypes.Add("FLOAT");
            listDataTypes.Add("FLOAT/INV");

            foreach (String item in listDataTypes)
            {
                this.cboDataTypeV1LL.Items.Add(item);
                this.cboDataTypeV2LL.Items.Add(item);
                this.cboDataTypeV3LL.Items.Add(item);
                this.cboDataTypeV1LN.Items.Add(item);
                this.cboDataTypeV2LN.Items.Add(item);
                this.cboDataTypeV3LN.Items.Add(item);
                this.cboDataTypeI1.Items.Add(item);
                this.cboDataTypeI2.Items.Add(item);
                this.cboDataTypeI3.Items.Add(item);
                this.cboDataTypeNI.Items.Add(item);
                this.cboDataTypeFreq.Items.Add(item);
                this.cboDataTypePF.Items.Add(item);
                this.cboDataTypeKW1.Items.Add(item);
                this.cboDataTypeKW2.Items.Add(item);
                this.cboDataTypeKW3.Items.Add(item);
                this.cboDataTypeKVA1.Items.Add(item);
                this.cboDataTypeKVA2.Items.Add(item);
                this.cboDataTypeKVA3.Items.Add(item);
                this.cboDataTypeKWH.Items.Add(item);
                this.cboDataTypeKVAH.Items.Add(item);
                this.cboDataTypeKVARH.Items.Add(item);
            }
        }

        // ---------------------------------------------------------------------------------------------------------- //
        // Event Handler For the Menu - Exit Function
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        // ---------------------------------------------------------------------------------------------------------- //
        // Event Handler for Setup Tab - Site Creation 
        private void cmdSetupSitesCreate_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<string, string>();

            if (txtSetupSitesInput.Text != "")
            {
                data.Add("NAMES", txtSetupSitesInput.Text);
                txtSetupSitesInput.Text = "";
                try
                {
                    db.Insert("SITES", data);
                } //try
                catch (Exception Ex)
                {
                    MessageBox.Show(Ex.Message);
                } //catch
            }
            else
            {
                MessageBox.Show("Supply Site Name","Site Name", MessageBoxButtons.OK, MessageBoxIcon.Information);
            } //else            
        }

        // Event Handler for Setup Tab - Site Modify
        private void cmdSetupSitesModify_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<string, string>();

            if (cboSetupSitesList.Text != "")
            {
                if (txtSetupSitesInput.Text != "")
                {
                    data.Add("NAMES", txtSetupSitesInput.Text);
                    try
                    {
                        db.Update("SITES", data, String.Format("NAMES=\"{0}\"", cboSetupSitesList.Text));                        
                        // Clear Input Box After UPdate
                        txtSetupSitesInput.Text = "";
                        // Update the ComboBox Display
                        cboSetupSitesList.SelectedIndex = -1;
                        cboSetupSitesList.Refresh();

                    } //try
                    catch (Exception Ex)
                    {
                        MessageBox.Show(Ex.Message);
                    } //catch
                }//if
                else
                {
                    MessageBox.Show("Please Enter Update Text", "Update Text", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("Select Site from DropDownBox", "Select Site", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        // Event Handler for Setup Tab - Site Deletion
        private void cmdSetupSitesDelete_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
 
            if (cboSetupSitesList.Text != "")
            {
                db.Delete("SITES", String.Format("NAMES=\"{0}\"", cboSetupSitesList.Text));
                
                // Update the ComboBox Display
                cboSetupSitesList.SelectedIndex = -1;
                cboSetupSitesList.Refresh();
            }
            else
            {
                MessageBox.Show("Select Site from DropDownBox", "Select Site", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        // Event Handler for Setup Tab - Site Listing
        private void cboSetupSitesList_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable dtSites;
            String query;
             
            query = "select NAMES \"Names\"";
            query += "from SITES";

            // clear ComboBox and Disable Enable
            cboSetupSitesList.Items.Clear();

            try
            {
                dtSites = db.GetDataTable(query);

                foreach (DataRow dr in dtSites.Rows)
                {
                    cboSetupSitesList.Items.Add(dr["Names"].ToString());
                }

            } //try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        }
        // ---------------------------------------------------------------------------------------------------------- //

        // ---------------------------------------------------------------------------------------------------------- //
        // Event Handler for Scale Tab - Scale Creation
        private void cmdScaleCreate_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<string, string>();

            // Make sure Text boxes got values
            if (txtScaleNameInput.Text != "" && 
                txtScaleIInput.Text != "" && 
                txtScaleVInput.Text != "" && 
                txtScaleWInput.Text != "" && 
                txtScaleEInput.Text != "" && 
                txtScaleHzInput.Text != "")
            {
                // Table Name, Input 
                data.Add("NAMES", txtScaleNameInput.Text);
                data.Add("I", txtScaleIInput.Text);
                data.Add("V", txtScaleVInput.Text);
                data.Add("W", txtScaleWInput.Text);
                data.Add("E", txtScaleEInput.Text);
                data.Add("Hz", txtScaleHzInput.Text);

                // Clear Text boxes
                txtScaleNameInput.Text = "";
                txtScaleIInput.Text = "";
                txtScaleVInput.Text = "";
                txtScaleWInput.Text = "";
                txtScaleEInput.Text = "";
                txtScaleHzInput.Text = "";

                try
                {
                    db.Insert("SCALE", data);
                } //try
                catch (Exception Ex)
                {
                    MessageBox.Show(Ex.Message);
                } //catch
            }
            else
            {
                MessageBox.Show("Scale Information Missing", "Scale Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            } //else
        } //method

        //Event Handler for Scale Tab - Scale Modify
        private void cmdScaleModify_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<string, string>();

            // Make sure Selection Dropdown box got value
            if (cboScaleList.Text != "")
            {
                if (txtScaleNameInput.Text != "")
                {
                    data.Add("NAMES", txtScaleNameInput.Text);
                }

                // Dropdown Box Input into DataTable
                data.Add("V", txtScaleVInput.Text);
                data.Add("I", txtScaleIInput.Text);
                data.Add("E", txtScaleEInput.Text);
                data.Add("W", txtScaleWInput.Text);
                data.Add("Hz", txtScaleHzInput.Text);

                // Clear Dropdown boxes
                txtScaleNameInput.Text = "";
                txtScaleVInput.Text = "";
                txtScaleIInput.Text = "";
                txtScaleEInput.Text = "";
                txtScaleWInput.Text = "";
                txtScaleHzInput.Text = "";

                try
                {
                    // Update Database
                    db.Update("SCALE", data, String.Format("NAMES=\"{0}\"", cboScaleList.Text));

                    // Refresh and Set DropDown Box
                    cboScaleList.SelectedIndex = -1;
                    cboScaleList.Refresh();
                } //try
                catch (Exception Ex)
                {
                    MessageBox.Show(Ex.Message);
                } //catch
            }
            else
            {
                MessageBox.Show("Scale Not Selected", "Scale Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
            } //else
        }

        // Event Handler for Scale Tab - Scale Deletion
        private void cmdScaleDelete_Click(object sender, EventArgs e)
        {            
            SQLiteDatabase db = new SQLiteDatabase();

            if (cboScaleList.Text != "")
            {
                db.Delete("SCALE", String.Format("NAMES=\"{0}\"", cboScaleList.Text));

                // Update the ComboBox Display
                cboScaleList.SelectedIndex = -1;
                cboScaleList.Refresh();
            }
            else
            {
                MessageBox.Show("Select Scale from DropDownBox", "Select Scale", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void cboScaleList_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable dtScale;
            String query;

            query = "select NAMES \"Names\"";
            query += "from SCALE";

            // clear ComboBox
            cboScaleList.Items.Clear();

            try
            {
                dtScale = db.GetDataTable(query);

                foreach (DataRow dr in dtScale.Rows)
                {
                    cboScaleList.Items.Add(dr["Names"].ToString());
                }
            } //try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        }

        private void cboScaleList_SelectedIndexChanged(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable dtScale;
            String sqlScale;

            sqlScale = "select V \"V\", I \"I\", E \"E\", W \"W\", Hz \"Hz\" ";
            sqlScale += "from SCALE ";
            sqlScale += String.Format("where NAMES=\"{0}\"", this.cboScaleList.Text);

            try
            {
                dtScale = db.GetDataTable(sqlScale);
                txtScaleNameInput.Text = "";

                foreach (DataRow dr in dtScale.Rows)
                {
                    txtScaleVInput.Text = dr["V"].ToString();
                    txtScaleIInput.Text = dr["I"].ToString();
                    txtScaleEInput.Text = dr["E"].ToString();
                    txtScaleWInput.Text = dr["W"].ToString();
                    txtScaleHzInput.Text = dr["Hz"].ToString();
                }
            } //try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        }
        // ---------------------------------------------------------------------------------------------------------- //

        private void cmdDataTypeCreate_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<string, string>();
            String sqlDataTypeScale;

            // Make sure Selection Dropdown boxes got values
            if (cboDataTypeV1LL.Text != "" && cboDataTypeV2LL.Text != "" && cboDataTypeV3LL.Text != "" &&
                cboDataTypeV1LN.Text != "" && cboDataTypeV2LN.Text != "" && cboDataTypeV3LN.Text != "" &&
                cboDataTypeI1.Text != "" && cboDataTypeI2.Text != "" && cboDataTypeI3.Text != "" &&
                cboDataTypeNI.Text != "" && cboDataTypeFreq.Text != "" && cboDataTypePF.Text != "" &&
                cboDataTypeKW1.Text != "" && cboDataTypeKW2.Text != "" && cboDataTypeKW3.Text != "" &&
                cboDataTypeKVA1.Text != "" && cboDataTypeKVA2.Text != "" && cboDataTypeKVA3.Text != "" &&
                cboDataTypeKWH.Text != "" && cboDataTypeKVAH.Text != "" && cboDataTypeKVARH.Text != "" &&
                cboDataTypeScale.Text != "" && txtDataTypeInput.Text != "")
             {
                //SQL Query to Get Scale ID for Scale Name
                sqlDataTypeScale = "select distinct ID ";
                sqlDataTypeScale += "from SCALE ";
                sqlDataTypeScale += String.Format("where NAMES=\"{0}\"", this.cboDataTypeScale.Text);

                // Dropdown Box Input into DataTable
                data.Add("NAMES", txtDataTypeInput.Text);
                data.Add("V1LL", cboDataTypeV1LL.Text);
                data.Add("V2LL", cboDataTypeV2LL.Text);
                data.Add("V3LL", cboDataTypeV3LL.Text);
                data.Add("V1LN", cboDataTypeV1LN.Text);
                data.Add("V2LN", cboDataTypeV2LN.Text);
                data.Add("V3LN", cboDataTypeV3LN.Text);
                data.Add("I1", cboDataTypeI1.Text);
                data.Add("I2", cboDataTypeI2.Text);
                data.Add("I3", cboDataTypeI3.Text);
                data.Add("NI", cboDataTypeNI.Text);
                data.Add("FREQ", cboDataTypeFreq.Text);
                data.Add("PF", cboDataTypePF.Text);
                data.Add("KW1", cboDataTypeKW1.Text);
                data.Add("KW2", cboDataTypeKW2.Text);
                data.Add("KW3", cboDataTypeKW3.Text);
                data.Add("KVA1", cboDataTypeKVA1.Text);
                data.Add("KVA2", cboDataTypeKVA2.Text);
                data.Add("KVA3", cboDataTypeKVA3.Text);
                data.Add("KWH", cboDataTypeKWH.Text);
                data.Add("KVAH", cboDataTypeKVAH.Text);
                data.Add("KVARH", cboDataTypeKVARH.Text);
                data.Add("SCALE_ID", db.ExecuteScalar(sqlDataTypeScale));

                // Clear Dropdown boxes
                txtDataTypeInput.Text = "";
                cboDataTypeV1LL.SelectedIndex = -1;
                cboDataTypeV2LL.SelectedIndex = -1;
                cboDataTypeV3LL.SelectedIndex = -1;
                cboDataTypeV1LN.SelectedIndex = -1;
                cboDataTypeV2LN.SelectedIndex = -1;
                cboDataTypeV3LN.SelectedIndex = -1;
                cboDataTypeI1.SelectedIndex = -1;
                cboDataTypeI2.SelectedIndex = -1;
                cboDataTypeI3.SelectedIndex = -1;
                cboDataTypeNI.SelectedIndex = -1;
                cboDataTypeFreq.SelectedIndex = -1;
                cboDataTypePF.SelectedIndex = -1;
                cboDataTypeKW1.SelectedIndex = -1;
                cboDataTypeKW2.SelectedIndex = -1;
                cboDataTypeKW3.SelectedIndex = -1;
                cboDataTypeKVA1.SelectedIndex = -1;
                cboDataTypeKVA2.SelectedIndex = -1;
                cboDataTypeKVA3.SelectedIndex = -1;
                cboDataTypeKWH.SelectedIndex = -1;
                cboDataTypeKVAH.SelectedIndex = -1;
                cboDataTypeKVARH.SelectedIndex = -1;
                cboDataTypeScale.SelectedIndex = -1;

                try
                {
                    db.Insert("DATATYPES", data);
                } //try
                catch (Exception Ex)
                {
                    MessageBox.Show(Ex.Message);
                } //catch
            }
            else
            {
                MessageBox.Show("Data Type Selection Missing", "Data Type", MessageBoxButtons.OK, MessageBoxIcon.Information);
            } //else
        }

        private void cmdDataTypeModify_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<string, string>();
            String sqlDataTypeScale;

            //SQL Query to Get Scale ID for Scale Name
            sqlDataTypeScale = "select distinct ID ";
            sqlDataTypeScale += "from SCALE ";
            sqlDataTypeScale += String.Format("where NAMES=\"{0}\"", this.cboDataTypeScale.Text);

            // Make sure Selection Dropdown box got value
            if (cboDataTypeList.Text != "")
            {
                // If textbox NOT empty then Update NAMES
                if (txtDataTypeInput.Text != "")
                {
                    data.Add("NAMES", txtDataTypeInput.Text);
                }//if

                // Dropdown Box Input into DataTable
                data.Add("V1LL", cboDataTypeV1LL.Text);
                data.Add("V2LL", cboDataTypeV2LL.Text);
                data.Add("V3LL", cboDataTypeV3LL.Text);
                data.Add("V1LN", cboDataTypeV1LN.Text);
                data.Add("V2LN", cboDataTypeV2LN.Text);
                data.Add("V3LN", cboDataTypeV3LN.Text);
                data.Add("I1", cboDataTypeI1.Text);
                data.Add("I2", cboDataTypeI2.Text);
                data.Add("I3", cboDataTypeI3.Text);
                data.Add("NI", cboDataTypeNI.Text);
                data.Add("FREQ", cboDataTypeFreq.Text);
                data.Add("PF", cboDataTypePF.Text);
                data.Add("KW1", cboDataTypeKW1.Text);
                data.Add("KW2", cboDataTypeKW2.Text);
                data.Add("KW3", cboDataTypeKW3.Text);
                data.Add("KVA1", cboDataTypeKVA1.Text);
                data.Add("KVA2", cboDataTypeKVA2.Text);
                data.Add("KVA3", cboDataTypeKVA3.Text);
                data.Add("KWH", cboDataTypeKWH.Text);
                data.Add("KVAH", cboDataTypeKVAH.Text);
                data.Add("KVARH", cboDataTypeKVARH.Text);
                data.Add("SCALE_ID", db.ExecuteScalar(sqlDataTypeScale));

                // Clear Dropdown boxes
                txtDataTypeInput.Text = "";
                cboDataTypeV1LL.SelectedIndex = -1;
                cboDataTypeV2LL.SelectedIndex = -1;
                cboDataTypeV3LL.SelectedIndex = -1;
                cboDataTypeV1LN.SelectedIndex = -1;
                cboDataTypeV2LN.SelectedIndex = -1;
                cboDataTypeV3LN.SelectedIndex = -1;
                cboDataTypeI1.SelectedIndex = -1;
                cboDataTypeI2.SelectedIndex = -1;
                cboDataTypeI3.SelectedIndex = -1;
                cboDataTypeNI.SelectedIndex = -1;
                cboDataTypeFreq.SelectedIndex = -1;
                cboDataTypePF.SelectedIndex = -1;
                cboDataTypeKW1.SelectedIndex = -1;
                cboDataTypeKW2.SelectedIndex = -1;
                cboDataTypeKW3.SelectedIndex = -1;
                cboDataTypeKVA1.SelectedIndex = -1;
                cboDataTypeKVA2.SelectedIndex = -1;
                cboDataTypeKVA3.SelectedIndex = -1;
                cboDataTypeKWH.SelectedIndex = -1;
                cboDataTypeKVAH.SelectedIndex = -1;
                cboDataTypeKVARH.SelectedIndex = -1;
                cboDataTypeScale.SelectedIndex = -1;

                try
                {
                    // Update Database
                    db.Update("DATATYPES", data, String.Format("NAMES=\"{0}\"", cboDataTypeList.Text));
                    
                    // Refresh and Set DropDown Box
                    cboDataTypeList.SelectedIndex = -1;
                    cboDataTypeList.Refresh();
                } //try
                catch (Exception Ex)
                {
                    MessageBox.Show(Ex.Message);
                } //catch
            }
            else
            {
                MessageBox.Show("Data Type Selection Missing", "Data Type Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
            } //else
        }

        private void cmdDataTypeDelete_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();

            if (cboDataTypeList.Text != "")
            {
                db.Delete("DATATYPES", String.Format("NAMES=\"{0}\"", cboDataTypeList.Text));

                // Update the ComboBox Display
                cboDataTypeList.SelectedIndex = -1;
                cboDataTypeList.Refresh();

                // Clear Dropdown boxes
                txtDataTypeInput.Text = "";
                cboDataTypeV1LL.SelectedIndex = -1;
                cboDataTypeV2LL.SelectedIndex = -1;
                cboDataTypeV3LL.SelectedIndex = -1;
                cboDataTypeV1LN.SelectedIndex = -1;
                cboDataTypeV2LN.SelectedIndex = -1;
                cboDataTypeV3LN.SelectedIndex = -1;
                cboDataTypeI1.SelectedIndex =   -1;
                cboDataTypeI2.SelectedIndex =   -1;
                cboDataTypeI3.SelectedIndex =   -1;
                cboDataTypeNI.SelectedIndex =   -1;
                cboDataTypeFreq.SelectedIndex = -1;
                cboDataTypePF.SelectedIndex =   -1;
                cboDataTypeKW1.SelectedIndex =  -1;
                cboDataTypeKW2.SelectedIndex =  -1;
                cboDataTypeKW3.SelectedIndex =  -1;
                cboDataTypeKVA1.SelectedIndex = -1;
                cboDataTypeKVA2.SelectedIndex = -1;
                cboDataTypeKVA3.SelectedIndex = -1;
                cboDataTypeKWH.SelectedIndex =  -1;
                cboDataTypeKVAH.SelectedIndex = -1;
                cboDataTypeKVARH.SelectedIndex = -1;
                cboDataTypeScale.SelectedIndex = -1;
            }
            else
            {
                MessageBox.Show("Select DataType from DropDownBox", "Select Data Type", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void cboDataTypeList_Click(object sender, EventArgs e)
        {
            int DataTypeCount;
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable dtDataType;
            String sqlDataType;

            sqlDataType = "select NAMES \"Names\"";
            sqlDataType += "from DATATYPES";

            try
            {
                dtDataType = db.GetDataTable(sqlDataType);
                DataTypeCount = Convert.ToInt32(dtDataType.Rows.Count.ToString());

                if (DataTypeCount > 0)
                {
                    // Clear the DropDown Box
                    cboDataTypeList.Items.Clear();

                    // Get Scale Names from Database
                    foreach (DataRow dr in dtDataType.Rows)
                    {
                        // Add Scale Names to DropDown Box
                        cboDataTypeList.Items.Add(dr["Names"].ToString());
                    }
                } //if
            } //try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch

        }

        // Update Controls when Selection Change
        private void cboDataTypeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();            
            DataTable dtDataType;
            DataTable dtScale;
            String sqlDataType;
            String sqlScale;

            sqlDataType = "select V1LL \"V1LL\", V2LL \"V2LL\", V3LL \"V3LL\", ";
            sqlDataType += "V1LN \"V1LN\", V2LN \"V2LN\", V3LN \"V3LN\", ";
            sqlDataType += "I1 \"I1\", I2 \"I2\", I3 \"I3\", NI \"NI\", ";
            sqlDataType += "FREQ \"FREQ\", PF \"PF\", ";
            sqlDataType += "KW1 \"KW1\", KW2 \"KW2\", KW3 \"KW3\", ";
            sqlDataType += "KVA1 \"KVA1\", KVA2 \"KVA2\", KVA3 \"KVA3\", ";
            sqlDataType += "KWH \"KWH\", KVAH \"KVAH\", KVARH \"KVARH\", SCALE.NAMES \"SCALE_NAME\" ";
            sqlDataType += "from DATATYPES, SCALE ";
            sqlDataType += "where DATATYPES.SCALE_ID = SCALE.ID ";
            sqlDataType += String.Format("AND DATATYPES.NAMES=\"{0}\"", this.cboDataTypeList.Text);

            sqlScale = "select NAMES \"Names\" ";
            sqlScale += "from SCALE";

            try
            {
                dtDataType = db.GetDataTable(sqlDataType);
                dtScale = db.GetDataTable(sqlScale);

                if (cboDataTypeList.Text != "")
                {
                    // Get Scale Items to fill Drop Down Box
                    cboDataTypeScale.Items.Clear();
                    foreach (DataRow dr in dtScale.Rows)
                    {
                        cboDataTypeScale.Items.Add(dr["Names"].ToString()); 
                    }//foreach

                    // Get DataTypes Names from Database
                    foreach (DataRow dr in dtDataType.Rows)
                    {
                        // Add Scale Names to DropDown Box
                        cboDataTypeV1LL.SelectedIndex = cboDataTypeV1LL.Items.IndexOf(dr["V1LL"].ToString());
                        cboDataTypeV2LL.SelectedIndex = cboDataTypeV2LL.Items.IndexOf(dr["V2LL"].ToString());
                        cboDataTypeV3LL.SelectedIndex = cboDataTypeV3LL.Items.IndexOf(dr["V3LL"].ToString());
                        cboDataTypeV1LN.SelectedIndex = cboDataTypeV1LN.Items.IndexOf(dr["V1LN"].ToString());
                        cboDataTypeV2LN.SelectedIndex = cboDataTypeV2LN.Items.IndexOf(dr["V2LN"].ToString());
                        cboDataTypeV3LN.SelectedIndex = cboDataTypeV3LN.Items.IndexOf(dr["V3LN"].ToString());
                        cboDataTypeI1.SelectedIndex = cboDataTypeI1.Items.IndexOf(dr["I1"].ToString());
                        cboDataTypeI2.SelectedIndex = cboDataTypeI2.Items.IndexOf(dr["I2"].ToString());
                        cboDataTypeI3.SelectedIndex = cboDataTypeI3.Items.IndexOf(dr["I3"].ToString());
                        cboDataTypeNI.SelectedIndex = cboDataTypeNI.Items.IndexOf(dr["NI"].ToString());
                        cboDataTypeFreq.SelectedIndex = cboDataTypeFreq.Items.IndexOf(dr["FREQ"].ToString());
                        cboDataTypePF.SelectedIndex = cboDataTypePF.Items.IndexOf(dr["PF"].ToString());
                        cboDataTypeKW1.SelectedIndex = cboDataTypeKW1.Items.IndexOf(dr["KW1"].ToString());
                        cboDataTypeKW2.SelectedIndex = cboDataTypeKW2.Items.IndexOf(dr["KW2"].ToString());
                        cboDataTypeKW3.SelectedIndex = cboDataTypeKW3.Items.IndexOf(dr["KW3"].ToString());
                        cboDataTypeKVA1.SelectedIndex = cboDataTypeKVA1.Items.IndexOf(dr["KVA1"].ToString());
                        cboDataTypeKVA2.SelectedIndex = cboDataTypeKVA2.Items.IndexOf(dr["KVA2"].ToString());
                        cboDataTypeKVA3.SelectedIndex = cboDataTypeKVA3.Items.IndexOf(dr["KVA3"].ToString());
                        cboDataTypeKWH.SelectedIndex = cboDataTypeKWH.Items.IndexOf(dr["KWH"].ToString());
                        cboDataTypeKVAH.SelectedIndex = cboDataTypeKVAH.Items.IndexOf(dr["KVAH"].ToString());
                        cboDataTypeKVARH.SelectedIndex = cboDataTypeKVARH.Items.IndexOf(dr["KVARH"].ToString());
                        cboDataTypeScale.SelectedIndex = cboDataTypeScale.Items.IndexOf(dr["SCALE_NAME"].ToString());
                    }//foreach
                } //if
            } //try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        }

        private void cboDataTypeScale_Click(object sender, EventArgs e)
        {
            int ScaleCount;
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable dtScale;
            String sqlScale;

            sqlScale = "select NAMES \"Names\"";
            sqlScale += "from SCALE";

            try
            {
                dtScale = db.GetDataTable(sqlScale);
                ScaleCount = Convert.ToInt32(dtScale.Rows.Count.ToString());

                if (ScaleCount > 0)
                {
                    // Clear the DropDown Box
                    cboDataTypeScale.Items.Clear();

                    // Get Scale Names from Database
                    foreach(DataRow dr in dtScale.Rows)
                    {
                        // Add Scale Names to DropDown Box
                        cboDataTypeScale.Items.Add(dr["Names"].ToString());
                    }
                } //if
            } //try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        }

        // ---------------------------------------------------------------------------------------------------------- //
        
        private void cmdMeterTypeCreate_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<string, string>();
            String sqlMeterDataType;

            // Make sure Text boxes got values
            if (txtMeterTypeInput.Text != "" && txtMeterTypeV1LL.Text != "" && txtMeterTypeV2LL.Text != "" && txtMeterTypeV3LL.Text != "" &&
                txtMeterTypeV1LN.Text != "" && txtMeterTypeV2LN.Text != "" && txtMeterTypeV3LN.Text != "" && txtMeterTypeI1.Text != "" &&
                txtMeterTypeI2.Text != "" && txtMeterTypeI3.Text != "" && txtMeterTypeIN.Text != "" && txtMeterTypeFreq.Text != "" &&
                txtMeterTypePF.Text != "" && txtMeterTypeKW1.Text != "" && txtMeterTypeKW2.Text != "" && txtMeterTypeKW3.Text != "" &&
                txtMeterTypeKVA1.Text != "" && txtMeterTypeKVA2.Text != "" && txtMeterTypeKVA3.Text != "" && txtMeterTypeKWH.Text != "" &&
                txtMeterTypeKVAH.Text != "" && txtMeterTypeKVARH.Text != "" && cboMeterTypeDataType.Text != "")
            {

                //SQL Query to Get Scale ID for Scale Name
                sqlMeterDataType = "select distinct ID ";
                sqlMeterDataType += "from DATATYPES ";
                sqlMeterDataType += String.Format("where NAMES=\"{0}\"", this.cboMeterTypeDataType.Text);

                // Dropdown Box Input into DataTable
                data.Add("NAMES", txtMeterTypeInput.Text);
                data.Add("V1LL", txtMeterTypeV1LL.Text);
                data.Add("V2LL", txtMeterTypeV2LL.Text);
                data.Add("V3LL", txtMeterTypeV3LL.Text);
                data.Add("V1LN", txtMeterTypeV1LN.Text);
                data.Add("V2LN", txtMeterTypeV2LN.Text);
                data.Add("V3LN", txtMeterTypeV3LN.Text);
                data.Add("I1", txtMeterTypeI1.Text);
                data.Add("I2", txtMeterTypeI2.Text);
                data.Add("I3", txtMeterTypeI3.Text);
                data.Add("NI", txtMeterTypeIN.Text);
                data.Add("FREQ", txtMeterTypeFreq.Text);
                data.Add("PF", txtMeterTypePF.Text);
                data.Add("KW1", txtMeterTypeKW1.Text);
                data.Add("KW2", txtMeterTypeKW2.Text);
                data.Add("KW3", txtMeterTypeKW3.Text);
                data.Add("KVA1", txtMeterTypeKVA1.Text);
                data.Add("KVA2", txtMeterTypeKVA2.Text);
                data.Add("KVA3", txtMeterTypeKVA3.Text);
                data.Add("KWH", txtMeterTypeKWH.Text);
                data.Add("KVAH", txtMeterTypeKVAH.Text);
                data.Add("KVARH", txtMeterTypeKVARH.Text);
                data.Add("DATATYPES_ID", db.ExecuteScalar(sqlMeterDataType));

                // Clear Dropdown boxes
                txtMeterTypeInput.Text = "";
                txtMeterTypeV1LL.Text = "";
                txtMeterTypeV2LL.Text = "";
                txtMeterTypeV3LL.Text = "";
                txtMeterTypeV1LN.Text = "";
                txtMeterTypeV2LN.Text = "";
                txtMeterTypeV3LN.Text = "";
                txtMeterTypeI1.Text = "";
                txtMeterTypeI2.Text = "";
                txtMeterTypeI3.Text = "";
                txtMeterTypeIN.Text = "";
                txtMeterTypeFreq.Text = "";
                txtMeterTypePF.Text = "";
                txtMeterTypeKW1.Text = "";
                txtMeterTypeKW2.Text = "";
                txtMeterTypeKW3.Text = "";
                txtMeterTypeKVA1.Text = "";
                txtMeterTypeKVA2.Text = "";
                txtMeterTypeKVA3.Text = "";
                txtMeterTypeKWH.Text = "";
                txtMeterTypeKVAH.Text = "";
                txtMeterTypeKVARH.Text = "";
                cboMeterTypeDataType.SelectedIndex = -1;

                try
                {
                    db.Insert("METERTYPES", data);
                } //try
                catch (Exception Ex)
                {
                    MessageBox.Show(Ex.Message);
                } //catch
            }
            else
            {
                MessageBox.Show("Meter Type Register Missing", "Meter Type", MessageBoxButtons.OK, MessageBoxIcon.Information);
            } //else
        }        

        private void cmdMeterTypeModify_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<string, string>();
            String sqlMeterDataType;

            //SQL Query to Get Scale ID for Scale Name
            sqlMeterDataType = "select distinct ID ";
            sqlMeterDataType += "from DATATYPES ";
            sqlMeterDataType += String.Format("where NAMES=\"{0}\"", this.cboMeterTypeDataType.Text);

            // Make sure Selection Dropdown box got value
            if (cboMeterTypeList.Text != "")
            {
                // If textbox NOT empty then Update NAMES
                if (txtMeterTypeInput.Text != "")
                {
                    data.Add("NAMES", txtMeterTypeInput.Text);
                }//if

                // Dropdown Box Input into DataTable
                data.Add("V1LL", txtMeterTypeV1LL.Text);
                data.Add("V2LL", txtMeterTypeV2LL.Text);
                data.Add("V3LL", txtMeterTypeV3LL.Text);
                data.Add("V1LN", txtMeterTypeV1LN.Text);
                data.Add("V2LN", txtMeterTypeV2LN.Text);
                data.Add("V3LN", txtMeterTypeV3LN.Text);
                data.Add("I1", txtMeterTypeI1.Text);
                data.Add("I2", txtMeterTypeI2.Text);
                data.Add("I3", txtMeterTypeI3.Text);
                data.Add("NI", txtMeterTypeIN.Text);
                data.Add("FREQ", txtMeterTypeFreq.Text);
                data.Add("PF", txtMeterTypePF.Text);
                data.Add("KW1", txtMeterTypeKW1.Text);
                data.Add("KW2", txtMeterTypeKW2.Text);
                data.Add("KW3", txtMeterTypeKW3.Text);
                data.Add("KVA1", txtMeterTypeKVA1.Text);
                data.Add("KVA2", txtMeterTypeKVA2.Text);
                data.Add("KVA3", txtMeterTypeKVA3.Text);
                data.Add("KWH", txtMeterTypeKWH.Text);
                data.Add("KVAH", txtMeterTypeKVAH.Text);
                data.Add("KVARH", txtMeterTypeKVARH.Text);
                data.Add("DATATYPES_ID", db.ExecuteScalar(sqlMeterDataType));

                // Clear Dropdown boxes
                txtMeterTypeInput.Text = "";
                txtMeterTypeV1LL.Text = "";
                txtMeterTypeV2LL.Text = "";
                txtMeterTypeV3LL.Text = "";
                txtMeterTypeV1LN.Text = "";
                txtMeterTypeV2LN.Text = "";
                txtMeterTypeV3LN.Text = "";
                txtMeterTypeI1.Text = "";
                txtMeterTypeI2.Text = "";
                txtMeterTypeI3.Text = "";
                txtMeterTypeIN.Text = "";
                txtMeterTypeFreq.Text = "";
                txtMeterTypePF.Text = "";
                txtMeterTypeKW1.Text = "";
                txtMeterTypeKW2.Text = "";
                txtMeterTypeKW3.Text = "";
                txtMeterTypeKVA1.Text = "";
                txtMeterTypeKVA2.Text = "";
                txtMeterTypeKVA3.Text = "";
                txtMeterTypeKWH.Text = "";
                txtMeterTypeKVAH.Text = "";
                txtMeterTypeKVARH.Text = "";
                cboMeterTypeDataType.SelectedIndex = -1;

                try
                {
                    // Update Database
                    db.Update("METERTYPES", data, String.Format("NAMES=\"{0}\"", cboMeterTypeList.Text));

                    // Refresh and Set DropDown Box
                    cboMeterTypeList.SelectedIndex = -1;
                    cboMeterTypeList.Refresh();
                } //try
                catch (Exception Ex)
                {
                    MessageBox.Show(Ex.Message);
                } //catch
            }
            else
            {
                MessageBox.Show("Meter Type Selection Missing", "Meter Type Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
            } //else
        }

        private void cmdMeterTypeDelete_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();

            if (cboMeterTypeList.Text != "")
            {
                db.Delete("METERTYPES", String.Format("NAMES=\"{0}\"", cboMeterTypeList.Text));

                // Update the ComboBox Display
                cboMeterTypeList.SelectedIndex = -1;
                cboMeterTypeList.Refresh();

                // Clear Dropdown boxes
                txtMeterTypeInput.Text = "";
                txtMeterTypeV1LL.Text = "";
                txtMeterTypeV2LL.Text = "";
                txtMeterTypeV3LL.Text = "";
                txtMeterTypeV1LN.Text = "";
                txtMeterTypeV2LN.Text = "";
                txtMeterTypeV3LN.Text = "";
                txtMeterTypeI1.Text = "";
                txtMeterTypeI2.Text = "";
                txtMeterTypeI3.Text = "";
                txtMeterTypeIN.Text = "";
                txtMeterTypeFreq.Text = "";
                txtMeterTypePF.Text = "";
                txtMeterTypeKW1.Text = "";
                txtMeterTypeKW2.Text = "";
                txtMeterTypeKW3.Text = "";
                txtMeterTypeKVA1.Text = "";
                txtMeterTypeKVA2.Text = "";
                txtMeterTypeKVA3.Text = "";
                txtMeterTypeKWH.Text = "";
                txtMeterTypeKVAH.Text = "";
                txtMeterTypeKVARH.Text = "";
                cboMeterTypeDataType.SelectedIndex = -1;
            }
            else
            {
                MessageBox.Show("Select Metertype from DropDownBox", "Select Meter Type", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void cboMeterTypeList_Click(object sender, EventArgs e)
        {
            int MeterTypeCount;
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable dtMeterType;
            String sqlMeterType;

            sqlMeterType = "select NAMES \"Names\"";
            sqlMeterType += "from METERTYPES";

            try
            {
                dtMeterType = db.GetDataTable(sqlMeterType);
                MeterTypeCount = Convert.ToInt32(dtMeterType.Rows.Count.ToString());

                if (MeterTypeCount > 0)
                {
                    // Clear the DropDown Box
                    cboMeterTypeList.Items.Clear();

                    // Get Scale Names from Database
                    foreach (DataRow dr in dtMeterType.Rows)
                    {
                        // Add Scale Names to DropDown Box
                        cboMeterTypeList.Items.Add(dr["Names"].ToString());
                    }
                } //if
            } //try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        }

        private void cboMeterTypeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable dtMetertype;
            DataTable dtDatatype;
            String sqlMetertype;
            String sqlDatatype;

            sqlMetertype = "select METERTYPES.V1LL \"V1LL\", METERTYPES.V2LL \"V2LL\", METERTYPES.V3LL \"V3LL\", ";
            sqlMetertype += "METERTYPES.V1LN \"V1LN\", METERTYPES.V2LN \"V2LN\", METERTYPES.V3LN \"V3LN\", ";
            sqlMetertype += "METERTYPES.I1 \"I1\", METERTYPES.I2 \"I2\", METERTYPES.I3 \"I3\", METERTYPES.NI \"NI\", ";
            sqlMetertype += "METERTYPES.FREQ \"FREQ\", METERTYPES.PF \"PF\", ";
            sqlMetertype += "METERTYPES.KW1 \"KW1\", METERTYPES.KW2 \"KW2\", METERTYPES.KW3 \"KW3\", ";
            sqlMetertype += "METERTYPES.KVA1 \"KVA1\", METERTYPES.KVA2 \"KVA2\", METERTYPES.KVA3 \"KVA3\", ";
            sqlMetertype += "METERTYPES.KWH \"KWH\", METERTYPES.KVAH \"KVAH\", METERTYPES.KVARH \"KVARH\", DATATYPES.NAMES \"DATATYPE_NAME\" ";
            sqlMetertype += "from METERTYPES, DATATYPES ";
            sqlMetertype += "where METERTYPES.DATATYPES_ID = DATATYPES.ID ";
            sqlMetertype += String.Format("AND METERTYPES.NAMES=\"{0}\"", this.cboMeterTypeList.Text);

            sqlDatatype = "select NAMES \"Names\" ";
            sqlDatatype += "from DATATYPES";

            try
            {
                dtMetertype = db.GetDataTable(sqlMetertype);
                dtDatatype = db.GetDataTable(sqlDatatype);

                if (cboMeterTypeList.Text != "")
                {
                    // Get Scale Items to fill Drop Down Box
                    cboMeterTypeDataType.Items.Clear();
                    foreach (DataRow dr in dtDatatype.Rows)
                    {
                        cboMeterTypeDataType.Items.Add(dr["Names"].ToString());
                    }//foreach

                    // Get DataTypes Names from Database
                    foreach (DataRow dr in dtMetertype.Rows)
                    {
                        txtMeterTypeV1LL.Text = dr["V1LL"].ToString();
                        txtMeterTypeV2LL.Text = dr["V2LL"].ToString();
                        txtMeterTypeV3LL.Text = dr["V3LL"].ToString();
                        txtMeterTypeV1LN.Text = dr["V1LN"].ToString();
                        txtMeterTypeV2LN.Text = dr["V2LN"].ToString();
                        txtMeterTypeV3LN.Text = dr["V3LN"].ToString();
                        txtMeterTypeI1.Text = dr["I1"].ToString();
                        txtMeterTypeI2.Text = dr["I2"].ToString();
                        txtMeterTypeI3.Text = dr["I3"].ToString();
                        txtMeterTypeIN.Text = dr["NI"].ToString();
                        txtMeterTypeFreq.Text = dr["FREQ"].ToString();
                        txtMeterTypePF.Text = dr["PF"].ToString();
                        txtMeterTypeKW1.Text = dr["KW1"].ToString();
                        txtMeterTypeKW2.Text = dr["KW2"].ToString();
                        txtMeterTypeKW3.Text = dr["KW3"].ToString();
                        txtMeterTypeKVA1.Text = dr["KVA1"].ToString();
                        txtMeterTypeKVA2.Text = dr["KVA2"].ToString();
                        txtMeterTypeKVA3.Text = dr["KVA3"].ToString();
                        txtMeterTypeKWH.Text = dr["KWH"].ToString();
                        txtMeterTypeKVAH.Text = dr["KVAH"].ToString();
                        txtMeterTypeKVARH.Text = dr["KVARH"].ToString();
                        cboMeterTypeDataType.SelectedIndex = cboMeterTypeDataType.Items.IndexOf(dr["DATATYPE_NAME"].ToString());
                    }//foreach
                } //if
            } //try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        }

        private void cboMeterTypeDataType_Click(object sender, EventArgs e)
        {
            int DataTypeCount;
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable dtDataType;
            String sqlDataType;

            sqlDataType = "select NAMES \"Names\"";
            sqlDataType += "from DATATYPES";

            try
            {
                dtDataType = db.GetDataTable(sqlDataType);
                DataTypeCount = Convert.ToInt32(dtDataType.Rows.Count.ToString());

                if (DataTypeCount > 0)
                {
                    // Clear the DropDown Box
                    cboMeterTypeDataType.Items.Clear();

                    // Get Scale Names from Database
                    foreach (DataRow dr in dtDataType.Rows)
                    {
                        // Add Scale Names to DropDown Box
                        cboMeterTypeDataType.Items.Add(dr["Names"].ToString());
                    }
                } //if
            } //try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        }
        // ---------------------------------------------------------------------------------------------------------- //

        // Event Handlers for Meter Allocation & Creation
        private void cmdMeterCreate_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<string, string>();
            String sqlSites;
            String sqlMeterType;

            //SQL Query to Get Site ID for Site Name
            sqlSites = "select distinct ID ";
            sqlSites += "from SITES ";
            sqlSites += String.Format("where NAMES=\"{0}\"", this.cboMeterSite.Text);

            //SQL Query to Get MeterType ID for Meter Name
            sqlMeterType = "select distinct ID ";
            sqlMeterType += "from METERTYPES ";
            sqlMeterType += String.Format("where NAMES=\"{0}\"", this.cboMeterType.Text);

            if (txtMeterInput.Text != "" && cboMeterQueryTime.Text != "" && cboMeterSite.Text != "" && 
                cboMeterType.Text != "" && cboMeterPort.Text != "" && cboMeterSlave.Text != "" &&
                cboMeterBaud.Text != "" && cboMeterDataBits.Text != "" && cboMeterParity.Text != "" && cboMeterStopBits.Text != "")
            {
                
                // Fill DataTable With Data
                data.Add("NAMES", txtMeterInput.Text);
                data.Add("QUERYTIME", cboMeterQueryTime.Text);
                data.Add("PORT", cboMeterPort.Text);
                data.Add("SLAVE", cboMeterSlave.Text);
                data.Add("SITES_ID", db.ExecuteScalar(sqlSites));
                data.Add("METERTYPES_ID", db.ExecuteScalar(sqlMeterType));
                data.Add("BAUD", cboMeterBaud.Text);
                data.Add("DATABITS", cboMeterDataBits.Text);
                data.Add("PARITY", cboMeterParity.Text);
                data.Add("STOPBITS", cboMeterStopBits.Text);

                // Clear DataTable
                txtMeterInput.Text = "";
                cboMeterQueryTime.SelectedIndex = -1;
                cboMeterSite.SelectedIndex = -1;
                cboMeterType.SelectedIndex = -1;
                cboMeterPort.SelectedIndex = -1;
                cboMeterSlave.SelectedIndex = -1;
                cboMeterBaud.SelectedIndex = -1;
                cboMeterDataBits.SelectedIndex = -1;
                cboMeterParity.SelectedIndex = -1;
                cboMeterStopBits.SelectedIndex = -1;

                try
                {
                    db.Insert("METERS", data);
                } //try
                catch (Exception Ex)
                {
                    MessageBox.Show(Ex.Message);
                } //catch
            }
            else
            {
                MessageBox.Show("Not All Fields Completed", "Meter Creation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }


        private void cmdMeterModify_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            Dictionary<String, String> data = new Dictionary<string, string>();
            String sqlSites;
            String sqlMeterType;

            //SQL Query to Get Site ID for Site Name
            sqlSites = "select distinct ID ";
            sqlSites += "from SITES ";
            sqlSites += String.Format("where NAMES=\"{0}\"", this.cboMeterSite.Text);

            //SQL Query to Get MeterType ID for Meter Name
            sqlMeterType = "select distinct ID ";
            sqlMeterType += "from METERTYPES ";
            sqlMeterType += String.Format("where NAMES=\"{0}\"", this.cboMeterType.Text);

            // Make sure Selection Dropdown box got value
            if (cboMeterList.Text != "")
            {
                // If textbox NOT empty then Update NAMES
                if (txtMeterInput.Text != "")
                {
                    data.Add("NAMES", txtMeterInput.Text);
                }//if

                // Dropdown Box Input into DataTable
                data.Add("QUERYTIME", cboMeterQueryTime.Text);
                data.Add("PORT", cboMeterPort.Text);
                data.Add("SLAVE", cboMeterSlave.Text);
                data.Add("SITES_ID", db.ExecuteScalar(sqlSites));
                data.Add("METERTYPES_ID", db.ExecuteScalar(sqlMeterType));
                data.Add("BAUD", cboMeterBaud.Text);
                data.Add("DATABITS", cboMeterDataBits.Text);
                data.Add("PARITY", cboMeterParity.Text);
                data.Add("STOPBITS", cboMeterStopBits.Text);

                // Clear Dropdown boxes
                txtMeterInput.Text = "";
                cboMeterQueryTime.SelectedIndex = -1;
                cboMeterSite.SelectedIndex = -1;
                cboMeterType.SelectedIndex = -1;
                cboMeterPort.SelectedIndex = -1;
                cboMeterSlave.SelectedIndex = -1;
                cboMeterBaud.SelectedIndex = -1;
                cboMeterDataBits.SelectedIndex = -1;
                cboMeterParity.SelectedIndex = -1;
                cboMeterStopBits.SelectedIndex = -1;

                try
                {
                    // Update Database
                    db.Update("METERS", data, String.Format("NAMES=\"{0}\"", cboMeterList.Text));

                    // Refresh and Set DropDown Box
                    cboMeterList.SelectedIndex = -1;
                    cboMeterList.Refresh();
                } //try
                catch (Exception Ex)
                {
                    MessageBox.Show(Ex.Message);
                } //catch
            }
            else
            {
                MessageBox.Show("Meter Not Selected", "Meter Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
            } //else
        }

        private void cmdMeterDelete_Click(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();

            if (cboMeterList.Text != "")
            {
                db.Delete("METERS", String.Format("NAMES=\"{0}\"", cboMeterList.Text));

                // Update the ComboBox Display
                cboMeterList.SelectedIndex = -1;
                cboMeterList.Refresh();

                // Clear Dropdown boxes
                txtMeterInput.Text = "";
                cboMeterQueryTime.SelectedIndex = -1;
                cboMeterSite.SelectedIndex = -1;
                cboMeterType.SelectedIndex = -1;
                cboMeterPort.SelectedIndex = -1;
                cboMeterSlave.SelectedIndex = -1;
                cboMeterBaud.SelectedIndex = -1;
                cboMeterDataBits.SelectedIndex = -1;
                cboMeterParity.SelectedIndex = -1;
                cboMeterStopBits.SelectedIndex = -1;
            }
            else
            {
                MessageBox.Show("Select Meter from DropDownBox", "Select Meter", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void cboMeterList_Click(object sender, EventArgs e)
        {
            int MeterCount;
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable dtMeter;
            String sqlMeter;

            sqlMeter = "select NAMES \"Names\"";
            sqlMeter += "from METERS";

            try
            {
                dtMeter = db.GetDataTable(sqlMeter);
                MeterCount = Convert.ToInt32(dtMeter.Rows.Count.ToString());

                if (MeterCount > 0)
                {
                    // Clear the DropDown Box
                    cboMeterList.Items.Clear();

                    // Get Meter Names from Database
                    foreach (DataRow dr in dtMeter.Rows)
                    {
                        // Add Meter Names to DropDown Box
                        cboMeterList.Items.Add(dr["Names"].ToString());
                    }
                } //if
            } //try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        }

        // Busy Implementing
        private void cboMeterList_SelectedIndexChanged(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable dtMeters;
            DataTable dtSites;
            DataTable dtMeterTypes;
            DataTable dtComPorts;

            String sqlMeters;
            String sqlSites;
            String sqlMeterTypes;
            String sqlComPorts;

            /*    
            METERS TABLE
            NAMES text
            QUERYTIME int
            SITES_ID int
            METERTYPES_ID int
            PORT text
            SLAVE int
             */

            sqlMeters = "select METERS.QUERYTIME \"QUERYTIME\", METERS.PORT \"PORT\", METERS.SLAVE \"SLAVE\", ";
            sqlMeters += "METERS.BAUD \"BAUD\", METERS.DATABITS \"DATABITS\", METERS.PARITY \"PARITY\", METERS.STOPBITS \"STOPBITS\", ";
            sqlMeters += "SITES.NAMES \"SITE_NAME\", METERTYPES.NAMES \"METERTYPE_NAME\" ";
            sqlMeters += "from METERS, SITES, METERTYPES ";
            sqlMeters += "where METERS.SITES_ID = SITES.ID ";
            sqlMeters += "and METERS.METERTYPES_ID = METERTYPES.ID ";
            sqlMeters += String.Format("and METERS.NAMES=\"{0}\"", this.cboMeterList.Text);

            sqlSites = "select NAMES \"Names\" ";
            sqlSites += "from SITES";

            sqlMeterTypes = "select NAMES \"Names\" ";
            sqlMeterTypes += "from METERTYPES";

            sqlComPorts = "select PORT \"Ports\" ";
            sqlComPorts += "from METERS";

            try
            {
                dtMeters = db.GetDataTable(sqlMeters);
                dtSites = db.GetDataTable(sqlSites);
                dtMeterTypes = db.GetDataTable(sqlMeterTypes);
                dtComPorts = db.GetDataTable(sqlComPorts);

                if (cboMeterList.Text != "")
                {
                    // Get Site Items to fill Drop Down Box
                    cboMeterSite.Items.Clear();
                    foreach (DataRow dr in dtSites.Rows)
                    {
                        cboMeterSite.Items.Add(dr["Names"].ToString());
                    }//foreach

                    // Get MeterType Items to fill Drop Down Box
                    cboMeterType.Items.Clear();
                    foreach (DataRow dr in dtMeterTypes.Rows)
                    {
                        cboMeterType.Items.Add(dr["Names"].ToString());
                    }//foreach

                    // Get COM PORTS to fill Drop Down Box from DATABASE, NOT SYSTEM.
                    cboMeterPort.Items.Clear();
                    foreach (DataRow dr in dtComPorts.Rows)
                    {
                        cboMeterPort.Items.Add(dr["Ports"].ToString());
                    }//foreach

                    // Get DataTypes Names from Database
                    foreach (DataRow dr in dtMeters.Rows)
                    {
                        cboMeterQueryTime.SelectedIndex = cboMeterQueryTime.Items.IndexOf(dr["QUERYTIME"].ToString());
                        cboMeterPort.SelectedIndex = cboMeterPort.Items.IndexOf(dr["PORT"].ToString()); 
                        cboMeterSlave.SelectedIndex = cboMeterSlave.Items.IndexOf(dr["SLAVE"].ToString());
                        cboMeterSite.SelectedIndex = cboMeterSite.Items.IndexOf(dr["SITE_NAME"].ToString());
                        cboMeterType.SelectedIndex = cboMeterType.Items.IndexOf(dr["METERTYPE_NAME"].ToString());                     
                        cboMeterBaud.SelectedIndex = cboMeterBaud.Items.IndexOf(dr["BAUD"].ToString());
                        cboMeterDataBits.SelectedIndex = cboMeterDataBits.Items.IndexOf(dr["DATABITS"].ToString());
                        cboMeterParity.SelectedIndex = cboMeterParity.Items.IndexOf(dr["PARITY"].ToString());
                        cboMeterStopBits.SelectedIndex = cboMeterStopBits.Items.IndexOf(dr["STOPBITS"].ToString());

                    }//foreach
                } //if
            } //try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        } 

        private void cboMeterQueryTime_Click(object sender, EventArgs e)
        {
            //Todo
        }

        private void cboMeterSite_Click(object sender, EventArgs e)
        {
            int SiteCount;
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable dtSites;
            String sqlSites;

            sqlSites = "select NAMES \"Names\"";
            sqlSites += "from SITES";

            try
            {
                dtSites = db.GetDataTable(sqlSites);
                SiteCount = Convert.ToInt32(dtSites.Rows.Count.ToString());

                if (SiteCount > 0)
                {
                    // Clear the DropDown Box
                    cboMeterSite.Items.Clear();

                    // Get Scale Names from Database
                    foreach (DataRow dr in dtSites.Rows)
                    {
                        // Add Sites Names to DropDown Box
                        cboMeterSite.Items.Add(dr["Names"].ToString());
                    }
                } //if
            } //try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        }

        private void cboMeterPort_Click(object sender, EventArgs e)
        {
            string[] comPorts; 
            
            // get avaliable Com Ports from OS
            comPorts= SerialPort.GetPortNames();

            // clear DropDownBox
            cboMeterPort.Items.Clear();

            // Iterate the array of Com Ports and Add to DropDownBox
            foreach (string port in comPorts)
            {
                cboMeterPort.Items.Add(port); 
            }
        }

        private void cboMeterType_Click(object sender, EventArgs e)
        {
            int MeterTypeCount;
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable dtMeterType;
            String sqlMeterType;

            sqlMeterType = "select NAMES \"Names\"";
            sqlMeterType += "from METERTYPES";

            try
            {
                dtMeterType = db.GetDataTable(sqlMeterType);
                MeterTypeCount = Convert.ToInt32(dtMeterType.Rows.Count.ToString());

                if (MeterTypeCount > 0)
                {
                    // Clear the DropDown Box
                    cboMeterType.Items.Clear();

                    // Get Scale Names from Database
                    foreach (DataRow dr in dtMeterType.Rows)
                    {
                        // Add MeterType Names to DropDown Box
                        cboMeterType.Items.Add(dr["Names"].ToString());
                    }
                } //if
            } //try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        }

        private void cboMeterSlave_Click(object sender, EventArgs e)
        {
            //Todo
        }
        // ---------------------------------------------------------------------------------------------------------- //
        
        // Main Tab Event Handler to Update Button Creation
        /* http://www.codewiz51.com/blog/post/2010/05/27/TabControl-the-SelectedIndexChanged-event-and-the-current-TabPage.aspx */
        private void tabControlMain_Click(object sender, EventArgs e)
        {
            TabPage tp = this.tabControlMain.SelectedTab;
            SQLiteDatabase db = new SQLiteDatabase();
            List<String> SitesListText = new List<String>();
            DataTable dtSites;
            String sqlSites;
            int iSiteCount;

            sqlSites = "select distinct SITES.NAMES \"Names\"";
            sqlSites += "from SITES, METERS ";
            sqlSites += "where SITES.ID = METERS.SITES_ID";

            try
            {
                dtSites = db.GetDataTable(sqlSites);
                iSiteCount = dtSites.Rows.Count;
                
                // check if Realtime not running first
                if(tabSetup.Enabled != false)
                {
                    if (iSiteCount > 0)
                    {
                        foreach (DataRow dr in dtSites.Rows)
                        {
                            SitesListText.Add(dr["Names"].ToString());
                        } //foreach

                        switch (tp.Text)
                        {
                            case "Realtime":
                                cmdRealtimeSites.createButtons(iSiteCount, SitesListText, cmdRealtimeSitesEventHandler);
                                cmdRealtimeSites.assignButtons(this.grpBoxRealtimeSites);

                                cmdHistoricSites.deleteButtons(this.grpBoxHistoricSites, cmdHistoricSitesEventHandler);
                                cmdHistoricMeters.deleteButtons(this.grpBoxHistoricMeters, cmdHistoricMetersEventHandler);

                                //Clear Global Site/Meter Selection for Historic
                                strHistoricSiteSelected = "";
                                strHistoricMeterSelected = "";

                                grhHistoricVoltsLL.clearCurves();
                                grhHistoricVoltsLN.clearCurves();
                                grhHistoricCurrent.clearCurves();
                                grhHistoricFreq.clearCurves();
                                grhHistoricPF.clearCurves();
                                grhHistoricRealPower.clearCurves();
                                grhHistoricReactivePower.clearCurves();

                                grhHistoricEnergy.clearHistoricBarCurves();                                
                            break;

                            case "Historic" :
                                cmdHistoricSites.createButtons(iSiteCount, SitesListText, cmdHistoricSitesEventHandler);
                                cmdHistoricSites.assignButtons(this.grpBoxHistoricSites);

                                cmdRealtimeSites.deleteButtons(this.grpBoxRealtimeSites, cmdRealtimeSitesEventHandler);
                                cmdRealtimeMeters.deleteButtons(this.grpBoxRealtimeMeters, cmdRealtimeMetersEventHandler);
                            break;

                            case "Setup":
                                cmdRealtimeSites.deleteButtons(this.grpBoxRealtimeSites, cmdRealtimeSitesEventHandler);
                                cmdRealtimeMeters.deleteButtons(this.grpBoxRealtimeMeters, cmdRealtimeMetersEventHandler);

                                cmdHistoricSites.deleteButtons(this.grpBoxHistoricSites, cmdHistoricSitesEventHandler);
                                cmdHistoricMeters.deleteButtons(this.grpBoxHistoricMeters, cmdHistoricMetersEventHandler);

                                //Clear Global Site/Meter Selection for Historic
                                strHistoricSiteSelected = "";
                                strHistoricMeterSelected = "";

                                grhHistoricVoltsLL.clearCurves();
                                grhHistoricVoltsLN.clearCurves();
                                grhHistoricCurrent.clearCurves();
                                grhHistoricFreq.clearCurves();
                                grhHistoricPF.clearCurves();
                                grhHistoricRealPower.clearCurves();
                                grhHistoricReactivePower.clearCurves();

                                grhHistoricEnergy.clearHistoricBarCurves();                                
                            break;
                        }//switch
                    }//if
                }//if
            }//try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        } //tabControlMain_Click

        private void cmdRealtimeSitesEventHandler(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            List<String> MetersListText = new List<String>();
            DataTable dtMeters;
            String sqlMeters;
            int iMetersCount;

            // Sites Related
            // Create local button object
            Button button = new Button();

            // Cast sender object to button type 
            button = (Button)sender;

            // Call Method to clear Selected Button Color
            cmdRealtimeSites.clearColorButton();     

            // Set Select Button Pressed & Assign Text for RealtimeGraph Start
            button.BackColor = Color.LightGreen;
            strRealtimeSiteSelected = button.Text;
            // Sites Related End

            sqlMeters = "select METERS.NAMES \"Names\"";
            sqlMeters += "from SITES, METERS ";
            sqlMeters += "where SITES.ID = METERS.SITES_ID ";
            sqlMeters += "and ";
            sqlMeters += String.Format("SITES.NAMES=\"{0}\"", button.Text);

            // Delete Meters from Box Control - as new Site Selection Selected
            cmdRealtimeMeters.deleteButtons(this.grpBoxRealtimeMeters, cmdRealtimeMetersEventHandler);

            try
            {
                dtMeters = db.GetDataTable(sqlMeters);
                iMetersCount = dtMeters.Rows.Count;

                if (iMetersCount > 0)
                {
                    // Get List from DataTable for Meter Names
                    foreach (DataRow dr in dtMeters.Rows)
                    {
                        MetersListText.Add(dr["Names"].ToString());
                    } //foreach

                    // Create and Assign Button for Meters
                    cmdRealtimeMeters.createButtons(iMetersCount, MetersListText, cmdRealtimeMetersEventHandler);
                    cmdRealtimeMeters.assignButtons(this.grpBoxRealtimeMeters);
                } //if
            }//try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        } //cmdRealtimeSitesEventHandler

        // Event Handler for RealtimeMeters
        private void cmdRealtimeMetersEventHandler(object sender, EventArgs e)
        {
            // Meters Related
            // Create local button object
            Button button = new Button();

            // CAST sender object to button type 
            button = (Button)sender;

            // Call Method to clear Selected Button Color
            cmdRealtimeMeters.clearColorButton();

            // Set Select Button Pressed & Assign Text for RealtimeGraph Start
            button.BackColor = Color.LightGreen;
            strRealtimeMeterSelected = button.Text;
            // Sites Related End
        } //cmdRealtimeMetersEventHandler

        private void cmdHistoricSitesEventHandler(object sender, EventArgs e)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            List<String> MetersListText = new List<String>();
            DataTable dtMeters;
            String sqlMeters;
            int iMetersCount;

            // Sites Related
            // Create local button object
            Button button = new Button();

            // Cast sender object to button type 
            button = (Button)sender;

            // Call Method to clear Selected Button Color
            cmdHistoricSites.clearColorButton();

            // Set Select Button Pressed
            button.BackColor = Color.LightGreen;
            strHistoricSiteSelected = button.Text;
            strHistoricMeterSelected = "";
            // Sites Related End

            sqlMeters = "select METERS.NAMES \"Names\"";
            sqlMeters += "from SITES, METERS ";
            sqlMeters += "where SITES.ID = METERS.SITES_ID ";
            sqlMeters += "and ";
            sqlMeters += String.Format("SITES.NAMES=\"{0}\"", button.Text);

            // Delete Meters from Box Control - as new Site Selection Selected
            cmdHistoricMeters.deleteButtons(this.grpBoxHistoricMeters, cmdHistoricMetersEventHandler);

            try
            {
                dtMeters = db.GetDataTable(sqlMeters);
                iMetersCount = dtMeters.Rows.Count;

                if (iMetersCount > 0)
                {
                    // Get List from DataTable for Meter Names
                    foreach (DataRow dr in dtMeters.Rows)
                    {
                        MetersListText.Add(dr["Names"].ToString());
                    } //foreach

                    // Create and Assign Button for Meters
                    cmdHistoricMeters.createButtons(iMetersCount, MetersListText, cmdHistoricMetersEventHandler);
                    cmdHistoricMeters.assignButtons(this.grpBoxHistoricMeters);
                } //if
            }//try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch
        } //cmdHistoricSitesEventHandler

        // Event Handler for RealtimeMeters Buttons
        private void cmdHistoricMetersEventHandler(object sender, EventArgs e)
        {
            // Meters Related
            // Create local button object
            Button button = new Button();

            // CAST sender object to button type 
            button = (Button)sender;
            strHistoricMeterSelected = button.Text;

            // Call Method to clear Selected Button Color
            cmdHistoricMeters.clearColorButton();

            // Set Select Button Pressed
            button.BackColor = Color.LightGreen;
            // Sites Related End

            tabControlHistoric_Click(tabControlHistoric, EventArgs.Empty);
        }
        // ---------------------------------------------------------------------------------------------------------- //

        // Historic Tab Event Handler
        private void tabControlHistoric_Click(object sender, EventArgs e)
        {
            TabPage tp = this.tabControlHistoric.SelectedTab;

            // Make Sure Site/Meter Selected
            if (strHistoricMeterSelected != "")
            {
                // Set Default DateTime Values for DateTime Picker
                dateTimePickerHistoricFrom.Value = DateTime.Now.AddDays(-1);
                dateTimePickerHistoricFrom.Value = DateTime.Now;

                switch (tp.Text)
                {
                    case "Volts/Current":
                        // Clear Selection Box first
                        this.cboHistoricSelection.Items.Clear();

                        // Load Drop Down Box with Values
                        this.cboHistoricSelection.Items.Add("Volts:LtoL");
                        this.cboHistoricSelection.Items.Add("Volts:LtoN");
                        this.cboHistoricSelection.Items.Add("Current");

                        // Set to Item index one
                        this.cboHistoricSelection.SelectedIndex = 0;

                        // Set Default Graph Options                    
                        this.grhHistoricVoltsLL.setGraphPane("Historic Voltage Graph", String.Format("Period FROM:{0} TO:{1}", dateTimePickerHistoricFrom.Text, dateTimePickerHistoricTo.Text), "Volts : LtoL");
                        this.grhHistoricVoltsLL.clearCurves();
                        this.grhHistoricVoltsLL.assignGraph(grpBoxHistoricGraphVoltsCurrent);

                        if (strHistoricMeterSelected != "")
                        {
                            updateHistoricGraph(cboHistoricSelection.Text, strHistoricMeterSelected, dateTimePickerHistoricFrom.Value, dateTimePickerHistoricTo.Value);
                        }
                        else
                        {
                            MessageBox.Show("Make Sure Meter Selected", "Historic Selection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }

                        // Break out of Switch
                        break;

                    case "Freq/PF":
                        // Clear Selection Box first
                        this.cboHistoricSelection.Items.Clear();

                        // Load Drop Down Box with Values
                        this.cboHistoricSelection.Items.Add("Frequency");
                        this.cboHistoricSelection.Items.Add("Power Factor");

                        // Set to Item index one
                        this.cboHistoricSelection.SelectedIndex = 0;

                        // Set Default Graph Options                    
                        this.grhHistoricFreq.setGraphPane("Historic Frequency Graph", String.Format("Period FROM:{0} TO:{1}", dateTimePickerHistoricFrom.Text, dateTimePickerHistoricTo.Text), "Hz");
                        this.grhHistoricFreq.clearCurves();
                        this.grhHistoricFreq.assignGraph(grpBoxHistoricGraphFreqPF);

                        if (strHistoricMeterSelected != "")
                        {
                            updateHistoricGraph(cboHistoricSelection.Text, strHistoricMeterSelected, dateTimePickerHistoricFrom.Value, dateTimePickerHistoricTo.Value);
                        }
                        else
                        {
                            MessageBox.Show("Make Sure Meter Selected", "Historic Selection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                        // Break out of Switch
                        break;

                    case "Power":
                        // Clear Selection Box first
                        this.cboHistoricSelection.Items.Clear();

                        // Load Drop Down Box with Values
                        this.cboHistoricSelection.Items.Add("KW");
                        this.cboHistoricSelection.Items.Add("KVA");

                        // Set to Item index one
                        this.cboHistoricSelection.SelectedIndex = 0;

                        // Set Default Graph Options                    
                        this.grhHistoricRealPower.setGraphPane("Historic RealPower Graph", String.Format("Period FROM:{0} TO:{1}", dateTimePickerHistoricFrom.Text, dateTimePickerHistoricTo.Text), "KW"); ;
                        this.grhHistoricRealPower.clearCurves();
                        this.grhHistoricRealPower.assignGraph(grpBoxHistoricGraphRealReactivePower);

                        if (strHistoricMeterSelected != "")
                        {
                            updateHistoricGraph(cboHistoricSelection.Text, strHistoricMeterSelected, dateTimePickerHistoricFrom.Value, dateTimePickerHistoricTo.Value);
                        }
                        else
                        {
                            MessageBox.Show("Make Sure Meter Selected", "Historic Selection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                        // Break out of Switch
                        break;

                    case "Energy":
                        // Clear Selection Box first
                        this.cboHistoricSelection.Items.Clear();

                        // Load Drop Down Box with Values
                        this.cboHistoricSelection.Items.Add("E_HOUR");
                        this.cboHistoricSelection.Items.Add("E_DAY");
                        this.cboHistoricSelection.Items.Add("E_MONTH");

                        // Set to Item index one
                        this.cboHistoricSelection.SelectedIndex = 0;

                        // Set Default Graph Options
                        this.grhHistoricEnergy.setGraphPane("Energy Per Day Grpah", String.Format("Period FROM:{0} TO:{1}", dateTimePickerHistoricFrom.Text, dateTimePickerHistoricTo.Text), "Energy(KWh/KVAh/KVARh)");
                        this.grhHistoricEnergy.clearHistoricBarCurves();
                        this.grhHistoricEnergy.assignGraph(grpBoxHistoricGraphEnergy);

                        // Break out of Switch
                        break;
                }//switch
            } //if
            else
            {
                MessageBox.Show("Make Sure Site/Meter Selected", "Historic Selection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            } //else  

        } //tabControlHistoric_Click

        public void updateHistoricGraph(string strSelection,string strMeter, DateTime dateFrom, DateTime dateTo)
        {
            /* Instance Variables */
            DateTime progDateTime = new DateTime();
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable dtDATALOG;
            DataTable dtMETERS;
            String sqlDATALOG15;
            String sqlDATALOG30;
            String sqlDATALOG60;
            String sqlMETERS;
            String sqlENERGYLOG15HOUR;
            String sqlENERGYLOG30HOUR;
            String sqlENERGYLOG60HOUR;

            String sqlENERGYLOG15DAY;
            String sqlENERGYLOG30DAY;
            String sqlENERGYLOG60DAY;

            String sqlENERGYLOG15MONTH;
            String sqlENERGYLOG30MONTH;
            String sqlENERGYLOG60MONTH;  

            int MeterQueryTime = 0;
            int MeterID = 0;

            sqlMETERS = "select distinct METERS.ID \"METERS_ID\", METERS.QUERYTIME \"QUERYTIME\" ";
            sqlMETERS += "from METERS ";
            sqlMETERS += String.Format("where METERS.NAMES=\"{0}\"", strMeter);

            try
            {
                dtMETERS = db.GetDataTable(sqlMETERS);

                foreach (DataRow dr in dtMETERS.Rows)
                {
                    MeterID = Convert.ToInt32(dr["METERS_ID"].ToString());
                    MeterQueryTime = Convert.ToInt32(dr["QUERYTIME"].ToString());
                } //foreach
            } //try
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            } //catch

            //String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));
            //DateTime dateFrom, DateTime dateTo

            sqlDATALOG15 = "select TIMESTAMP \"TIMESTAMP\", V1LL \"V1LL\", V2LL \"V2LL\", V3LL \"V3LL\", V1LN \"V1LN\", V2LN \"V2LN\", V3LN \"V3LN\", ";
            sqlDATALOG15 += "I1 \"I1\", I2 \"I2\", I3 \"I3\", NI \"NI\", ";
            sqlDATALOG15 += "FREQ \"FREQ\", PF \"PF\", ";
            sqlDATALOG15 += "KW1 \"KW1\", KW2 \"KW2\", KW3 \"KW3\", ";
            sqlDATALOG15 += "KVA1 \"KVA1\", KVA2 \"KVA2\", KVA3 \"KVA3\" ";            
            sqlDATALOG15 += "from DATALOG15 ";
            sqlDATALOG15 += String.Format("where METERS_ID=\"{0}\"", MeterID.ToString());
            sqlDATALOG15 += String.Format("and TIMESTAMP >=\"{0}\"", String.Format("{0:yyyy-MM-dd HH:mm:ss}", dateFrom));
            sqlDATALOG15 += String.Format("and TIMESTAMP <=\"{0}\"", String.Format("{0:yyyy-MM-dd HH:mm:ss}", dateTo));

            sqlDATALOG30 = "select TIMESTAMP \"TIMESTAMP\", V1LL \"V1LL\", V2LL \"V2LL\", V3LL \"V3LL\", V1LN \"V1LN\", V2LN \"V2LN\", V3LN \"V3LN\", ";
            sqlDATALOG30 += "I1 \"I1\", I2 \"I2\", I3 \"I3\", NI \"NI\", ";
            sqlDATALOG30 += "FREQ \"FREQ\", PF \"PF\", ";
            sqlDATALOG30 += "KW1 \"KW1\", KW2 \"KW2\", KW3 \"KW3\", ";
            sqlDATALOG30 += "KVA1 \"KVA1\", KVA2 \"KVA2\", KVA3 \"KVA3\" ";            
            sqlDATALOG30 += "from DATALOG30 ";
            sqlDATALOG30 += String.Format("where METERS_ID=\"{0}\"", MeterID.ToString());
            sqlDATALOG30 += String.Format("and TIMESTAMP >=\"{0}\"", String.Format("{0:yyyy-MM-dd HH:mm:ss}", dateFrom));
            sqlDATALOG30 += String.Format("and TIMESTAMP <=\"{0}\"", String.Format("{0:yyyy-MM-dd HH:mm:ss}", dateTo));

            sqlDATALOG60 = "select TIMESTAMP \"TIMESTAMP\", V1LL \"V1LL\", V2LL \"V2LL\", V3LL \"V3LL\", V1LN \"V1LN\", V2LN \"V2LN\", V3LN \"V3LN\", ";
            sqlDATALOG60 += "I1 \"I1\", I2 \"I2\", I3 \"I3\", NI \"NI\", ";
            sqlDATALOG60 += "FREQ \"FREQ\", PF \"PF\", ";
            sqlDATALOG60 += "KW1 \"KW1\", KW2 \"KW2\", KW3 \"KW3\", ";
            sqlDATALOG60 += "KVA1 \"KVA1\", KVA2 \"KVA2\", KVA3 \"KVA3\" ";            
            sqlDATALOG60 += "from DATALOG60 ";
            sqlDATALOG60 += String.Format("where METERS_ID=\"{0}\"", MeterID.ToString());
            sqlDATALOG60 += String.Format("and TIMESTAMP >=\"{0}\"", String.Format("{0:yyyy-MM-dd HH:mm:ss}", dateFrom));
            sqlDATALOG60 += String.Format("and TIMESTAMP <=\"{0}\"", String.Format("{0:yyyy-MM-dd HH:mm:ss}", dateTo));

            // Energy Datalog query - HOUR15 Period
            sqlENERGYLOG15HOUR = "select strftime('%H:59',DATALOG15.TIMESTAMP) AS TIMESTAMP, MAX(KWH) - MIN(KWH) AS KWH_CAL, MAX(KVAH) - MIN(KVAH) AS KVAH_CAL, MAX(KVARH) - MIN(KVARH) AS KVARH_CAL ";
            sqlENERGYLOG15HOUR += "from DATALOG15 ";
            sqlENERGYLOG15HOUR += String.Format("where KWH != '0' and KVAH != '0' and KVARH != '0' and METERS_ID=\"{0}\" ", MeterID.ToString());
            sqlENERGYLOG15HOUR += String.Format("and TIMESTAMP >=\"{0}\" ", String.Format("{0:yyyy-MM-dd} 00:00:00", dateTo));
            sqlENERGYLOG15HOUR += String.Format("and TIMESTAMP <=\"{0}\" ", String.Format("{0:yyyy-MM-dd} 23:59:59", dateTo));
            sqlENERGYLOG15HOUR += "group by strftime('%H',TIMESTAMP)";

            // Energy Datalog query - HOUR30 Period
            sqlENERGYLOG30HOUR = "select strftime('%H:59',DATALOG30.TIMESTAMP) AS TIMESTAMP, MAX(KWH) - MIN(KWH) AS KWH_CAL, MAX(KVAH) - MIN(KVAH) AS KVAH_CAL, MAX(KVARH) - MIN(KVARH) AS KVARH_CAL ";
            sqlENERGYLOG30HOUR += "from DATALOG30 ";
            sqlENERGYLOG30HOUR += String.Format("where KWH != '0' and KVAH != '0' and KVARH != '0' and METERS_ID=\"{0}\" ", MeterID.ToString());
            sqlENERGYLOG30HOUR += String.Format("and TIMESTAMP >=\"{0}\" ", String.Format("{0:yyyy-MM-dd} 00:00:00", dateTo));
            sqlENERGYLOG30HOUR += String.Format("and TIMESTAMP <=\"{0}\" ", String.Format("{0:yyyy-MM-dd} 23:59:59", dateTo));
            sqlENERGYLOG30HOUR += "group by strftime('%H',TIMESTAMP)";

            // Energy Datalog query - HOUR60 Period
            sqlENERGYLOG60HOUR = "select strftime('%H:59',DATALOG60.TIMESTAMP) AS TIMESTAMP, MAX(KWH) - MIN(KWH) AS KWH_CAL, MAX(KVAH) - MIN(KVAH) AS KVAH_CAL, MAX(KVARH) - MIN(KVARH) AS KVARH_CAL ";
            sqlENERGYLOG60HOUR += "from DATALOG60 ";
            sqlENERGYLOG60HOUR += String.Format("where KWH != '0' and KVAH != '0' and KVARH != '0' and METERS_ID=\"{0}\" ", MeterID.ToString());
            sqlENERGYLOG60HOUR += String.Format("and TIMESTAMP >=\"{0}\" ", String.Format("{0:yyyy-MM-dd} 00:00:00", dateTo));
            sqlENERGYLOG60HOUR += String.Format("and TIMESTAMP <=\"{0}\" ", String.Format("{0:yyyy-MM-dd} 23:59:59", dateTo));
            sqlENERGYLOG60HOUR += "group by strftime('%H',TIMESTAMP)";

            
            // Energy Datalog query - DAY15 Period
            sqlENERGYLOG15DAY = "select strftime('%Y/%m/%d',DATALOG15.TIMESTAMP) AS TIMESTAMP, MAX(KWH) - MIN(KWH) AS KWH_CAL, MAX(KVAH) - MIN(KVAH) AS KVAH_CAL, MAX(KVARH) - MIN(KVARH) AS KVARH_CAL ";
            sqlENERGYLOG15DAY += "from DATALOG15 ";
            sqlENERGYLOG15DAY += String.Format("where KWH != '0' and KVAH != '0' and KVARH != '0' and METERS_ID=\"{0}\" ", MeterID.ToString());
            sqlENERGYLOG15DAY += String.Format("and TIMESTAMP >=\"{0}\" ", String.Format("{0:yyyy-MM-00} 00:00:00", dateTo));
            sqlENERGYLOG15DAY += String.Format("and TIMESTAMP <=\"{0}\" ", String.Format("{0:yyyy-MM-31} 23:59:59", dateTo));
            sqlENERGYLOG15DAY += "group by strftime('%Y/%m/%d',TIMESTAMP)";

            // Energy Datalog query - DAY30 Period
            sqlENERGYLOG30DAY = "select strftime('%Y/%m/%d',DATALOG30.TIMESTAMP) AS TIMESTAMP, MAX(KWH) - MIN(KWH) AS KWH_CAL, MAX(KVAH) - MIN(KVAH) AS KVAH_CAL, MAX(KVARH) - MIN(KVARH) AS KVARH_CAL ";
            sqlENERGYLOG30DAY += "from DATALOG30 ";
            sqlENERGYLOG30DAY += String.Format("where KWH != '0' and KVAH != '0' and KVARH != '0' and METERS_ID=\"{0}\" ", MeterID.ToString());
            sqlENERGYLOG30DAY += String.Format("and TIMESTAMP >=\"{0}\" ", String.Format("{0:yyyy-MM-00} 00:00:00", dateTo));
            sqlENERGYLOG30DAY += String.Format("and TIMESTAMP <=\"{0}\" ", String.Format("{0:yyyy-MM-31} 23:59:59", dateTo));
            sqlENERGYLOG30DAY += "group by strftime('%Y/%m/%d',TIMESTAMP)";

            // Energy Datalog query - DAY60 Period
            sqlENERGYLOG60DAY = "select strftime('%Y/%m/%d',DATALOG60.TIMESTAMP) AS TIMESTAMP, MAX(KWH) - MIN(KWH) AS KWH_CAL, MAX(KVAH) - MIN(KVAH) AS KVAH_CAL, MAX(KVARH) - MIN(KVARH) AS KVARH_CAL ";
            sqlENERGYLOG60DAY += "from DATALOG60 ";
            sqlENERGYLOG60DAY += String.Format("where KWH != '0' and KVAH != '0' and KVARH != '0' and METERS_ID=\"{0}\" ", MeterID.ToString());
            sqlENERGYLOG60DAY += String.Format("and TIMESTAMP >=\"{0}\" ", String.Format("{0:yyyy-MM-00} 00:00:00", dateTo));
            sqlENERGYLOG60DAY += String.Format("and TIMESTAMP <=\"{0}\" ", String.Format("{0:yyyy-MM-31} 23:59:59", dateTo));
            sqlENERGYLOG60DAY += "group by strftime('%Y/%m/%d',TIMESTAMP)";

            // Energy Datalog query - MONTH15 Period
            sqlENERGYLOG15MONTH = "select strftime('%Y/%m',DATALOG15.TIMESTAMP) AS TIMESTAMP, MAX(KWH) - MIN(KWH) AS KWH_CAL, MAX(KVAH) - MIN(KVAH) AS KVAH_CAL, MAX(KVARH) - MIN(KVARH) AS KVARH_CAL ";
            sqlENERGYLOG15MONTH += "from DATALOG15 ";
            sqlENERGYLOG15MONTH += String.Format("where KWH != '0' and KVAH != '0' and KVARH != '0' and METERS_ID=\"{0}\" ", MeterID.ToString());
            sqlENERGYLOG15MONTH += String.Format("and TIMESTAMP >=\"{0}\" ", String.Format("{0:yyyy-01-01} 00:00:00", dateTo));
            sqlENERGYLOG15MONTH += String.Format("and TIMESTAMP <=\"{0}\" ", String.Format("{0:yyyy-12-31} 23:59:59", dateTo));
            sqlENERGYLOG15MONTH += "group by strftime('%Y/%m',TIMESTAMP)";

            // Energy Datalog query - MONTH15 Period
            sqlENERGYLOG30MONTH = "select strftime('%Y/%m',DATALOG30.TIMESTAMP) AS TIMESTAMP, MAX(KWH) - MIN(KWH) AS KWH_CAL, MAX(KVAH) - MIN(KVAH) AS KVAH_CAL, MAX(KVARH) - MIN(KVARH) AS KVARH_CAL ";
            sqlENERGYLOG30MONTH += "from DATALOG30 ";
            sqlENERGYLOG30MONTH += String.Format("where KWH != '0' and KVAH != '0' and KVARH != '0' and METERS_ID=\"{0}\" ", MeterID.ToString());
            sqlENERGYLOG30MONTH += String.Format("and TIMESTAMP >=\"{0}\" ", String.Format("{0:yyyy-01-01} 00:00:00", dateTo));
            sqlENERGYLOG30MONTH += String.Format("and TIMESTAMP <=\"{0}\" ", String.Format("{0:yyyy-12-31} 23:59:59", dateTo));
            sqlENERGYLOG30MONTH += "group by strftime('%Y/%m',TIMESTAMP)";

            // Energy Datalog query - MONTH15 Period
            sqlENERGYLOG60MONTH = "select strftime('%Y/%m',DATALOG60.TIMESTAMP) AS TIMESTAMP, MAX(KWH) - MIN(KWH) AS KWH_CAL, MAX(KVAH) - MIN(KVAH) AS KVAH_CAL, MAX(KVARH) - MIN(KVARH) AS KVARH_CAL ";
            sqlENERGYLOG60MONTH += "from DATALOG60 ";
            sqlENERGYLOG60MONTH += String.Format("where KWH != '0' and KVAH != '0' and KVARH != '0' and METERS_ID=\"{0}\" ", MeterID.ToString());
            sqlENERGYLOG60MONTH += String.Format("and TIMESTAMP >=\"{0}\" ", String.Format("{0:yyyy-01-01} 00:00:00", dateTo));
            sqlENERGYLOG60MONTH += String.Format("and TIMESTAMP <=\"{0}\" ", String.Format("{0:yyyy-12-31} 23:59:59", dateTo));
            sqlENERGYLOG60MONTH += "group by strftime('%Y/%m',TIMESTAMP)";
            
            switch (strSelection)
            {
                // Voltage & Current Graph Selection
                case "Volts:LtoL":

                    // Set Default Graph Options
                    this.grhHistoricVoltsLL.assignGraph(grpBoxHistoricGraphVoltsCurrent);
                    this.grhHistoricVoltsLL.setGraphPane(String.Format("Historic Voltage Graph@{0}", strMeter), String.Format("Period FROM:{0} TO:{1}", dateTimePickerHistoricFrom.Text, dateTimePickerHistoricTo.Text), "Volts : LtoL");
                    this.grhHistoricVoltsLL.clearCurves();

                    switch (MeterQueryTime)
                    {
                        case 15:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG15);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricVoltsLL.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["V1LL"]), Convert.ToDouble(dr["V2LL"]), Convert.ToDouble(dr["V3LL"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                        case 30:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG30);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricVoltsLL.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["V1LL"]), Convert.ToDouble(dr["V2LL"]), Convert.ToDouble(dr["V3LL"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                        case 60:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG60);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricVoltsLL.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["V1LL"]), Convert.ToDouble(dr["V2LL"]), Convert.ToDouble(dr["V3LL"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                    }//switch
                    break;

                case "Volts:LtoN":

                    // Set Default Graph Options 
                    this.grhHistoricVoltsLN.assignGraph(grpBoxHistoricGraphVoltsCurrent);
                    this.grhHistoricVoltsLN.setGraphPane(String.Format("Historic Voltage Graph@{0}", strMeter), String.Format("Period FROM:{0} TO:{1}", dateTimePickerHistoricFrom.Text, dateTimePickerHistoricTo.Text), "Volts : LtoN");
                    this.grhHistoricVoltsLN.clearCurves();
                    
                    switch (MeterQueryTime)
                    {
                        case 15:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG15);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricVoltsLN.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["V1LN"]), Convert.ToDouble(dr["V2LN"]), Convert.ToDouble(dr["V3LN"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                        case 30:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG30);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricVoltsLN.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["V1LN"]), Convert.ToDouble(dr["V2LN"]), Convert.ToDouble(dr["V3LN"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                        case 60:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG60);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricVoltsLN.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["V1LN"]), Convert.ToDouble(dr["V2LN"]), Convert.ToDouble(dr["V3LN"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                    }//switch
                    break;

                case "Current":

                    // Set Default Graph Options 
                    this.grhHistoricCurrent.assignGraph(grpBoxHistoricGraphVoltsCurrent);
                    this.grhHistoricCurrent.setGraphPane(String.Format("Historic Current Graph@{0}", strMeter), String.Format("Period FROM:{0} TO:{1}", dateTimePickerHistoricFrom.Text, dateTimePickerHistoricTo.Text), "Amps (I)");
                    this.grhHistoricCurrent.clearCurves();

                    switch (MeterQueryTime)
                    {
                        case 15:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG15);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricCurrent.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["I1"]), Convert.ToDouble(dr["I2"]), Convert.ToDouble(dr["I3"]), Convert.ToDouble(dr["NI"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                        case 30:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG30);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricCurrent.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["I1"]), Convert.ToDouble(dr["I2"]), Convert.ToDouble(dr["I3"]), Convert.ToDouble(dr["NI"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                        case 60:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG60);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricCurrent.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["I1"]), Convert.ToDouble(dr["I2"]), Convert.ToDouble(dr["I3"]), Convert.ToDouble(dr["NI"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                    }//switch
                    break;

                // Frequency & Power Factor Graph Selection
                case "Frequency":

                    // Set Default Graph Options                    
                    this.grhHistoricFreq.setGraphPane(String.Format("Historic Frequency Graph@{0}", strMeter), String.Format("Period FROM:{0} TO:{1}", dateTimePickerHistoricFrom.Text, dateTimePickerHistoricTo.Text), "Hz");
                    this.grhHistoricFreq.clearCurves();
                    this.grhHistoricFreq.assignGraph(grpBoxHistoricGraphFreqPF);

                    switch (MeterQueryTime)
                    {
                        case 15:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG15);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricFreq.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["FREQ"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                        case 30:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG30);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricFreq.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["FREQ"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                        case 60:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG60);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricFreq.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["FREQ"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                    }//switch
                    break;

                    

                case "Power Factor":

                    // Set Default Graph Options                    
                    this.grhHistoricPF.setGraphPane(String.Format("Historic Power Factor Graph@{0}",strMeter), String.Format("Period FROM:{0} TO:{1}", dateTimePickerHistoricFrom.Text, dateTimePickerHistoricTo.Text), "PF");
                    this.grhHistoricPF.clearCurves();
                    this.grhHistoricPF.assignGraph(grpBoxHistoricGraphFreqPF);

                    switch (MeterQueryTime)
                    {
                        case 15:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG15);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricPF.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["PF"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                        case 30:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG30);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricPF.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["PF"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                        case 60:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG60);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricPF.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["PF"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                    }//switch
                    break;

                // Power Selection - KW/KVA
                case "KW":

                    // Set Default Graph Options                    
                    this.grhHistoricRealPower.setGraphPane(String.Format("Historic RealPower Graph@{0}",strMeter), String.Format("Period FROM:{0} TO:{1}", dateTimePickerHistoricFrom.Text, dateTimePickerHistoricTo.Text), "KW");
                    this.grhHistoricRealPower.clearCurves();
                    this.grhHistoricRealPower.assignGraph(grpBoxHistoricGraphRealReactivePower);

                    switch (MeterQueryTime)
                    {
                        case 15:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG15);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricRealPower.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["KW1"]), Convert.ToDouble(dr["KW2"]), Convert.ToDouble(dr["KW3"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                        case 30:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG30);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricRealPower.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["KW1"]), Convert.ToDouble(dr["KW2"]), Convert.ToDouble(dr["KW3"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                        case 60:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG60);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricRealPower.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["KW1"]), Convert.ToDouble(dr["KW2"]), Convert.ToDouble(dr["KW3"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                    }//switch
                    break;

                case "KVA":

                    // Set Default Graph Options                    
                    this.grhHistoricReactivePower.setGraphPane(String.Format("Historic Reactive Power Graph@{0}",strMeter), String.Format("Period FROM:{0} TO:{1}", dateTimePickerHistoricFrom.Text, dateTimePickerHistoricTo.Text), "KVA");
                    this.grhHistoricReactivePower.clearCurves();
                    this.grhHistoricReactivePower.assignGraph(grpBoxHistoricGraphRealReactivePower);

                    switch (MeterQueryTime)
                    {
                        case 15:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG15);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricReactivePower.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["KVA1"]), Convert.ToDouble(dr["KVA2"]), Convert.ToDouble(dr["KVA3"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                        case 30:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG30);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricReactivePower.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["KVA1"]), Convert.ToDouble(dr["KVA2"]), Convert.ToDouble(dr["KVA3"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                        case 60:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlDATALOG60);

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    progDateTime = DateTime.Parse(dr["TIMESTAMP"].ToString());

                                    this.grhHistoricReactivePower.updateHistoricCurves(progDateTime, Convert.ToDouble(dr["KVA1"]), Convert.ToDouble(dr["KVA2"]), Convert.ToDouble(dr["KVA3"]));
                                }//foreach
                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch

                            break;
                    }//switch
                    break;

                case "E_HOUR"   :

                    // Set Default Graph Options
                    this.grhHistoricEnergy.setGraphPane(String.Format("Historic Energy Hour Graph@{0}", strMeter), String.Format("For DAY:{0}/{1}/{2}", dateTimePickerHistoricTo.Value.Day, dateTimePickerHistoricTo.Value.Month, dateTimePickerHistoricTo.Value.Year), "Energy(KWh/KVAh/KVARh)");
                    this.grhHistoricEnergy.clearHistoricBarCurves();
                    this.grhHistoricEnergy.assignGraph(grpBoxHistoricGraphEnergy);

                    switch (MeterQueryTime)
                    {
                        case 15:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlENERGYLOG15HOUR);

                                //Data Containers
                                List<DateTime> datetime = new List<DateTime>();
                                List<double> kwh = new List<double>();
                                List<double> kvah = new List<double>();
                                List<double> kvarh = new List<double>();

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    datetime.Add(DateTime.Parse(dr["TIMESTAMP"].ToString()));
                                    kwh.Add(Convert.ToDouble(dr["KWH_CAL"]));
                                    kvah.Add(Convert.ToDouble(dr["KVAH_CAL"]));
                                    kvarh.Add(Convert.ToDouble(dr["KVARH_CAL"]));
                                }//foreach

                                // Create the Bar Graph
                                this.grhHistoricEnergy.updateHistoricBarCurves(datetime, kwh, kvah, kvarh, "%h");

                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch
                            break;

                        case 30:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlENERGYLOG30HOUR);

                                //Data Containers
                                List<DateTime> datetime = new List<DateTime>();
                                List<double> kwh = new List<double>();
                                List<double> kvah = new List<double>();
                                List<double> kvarh = new List<double>();

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    datetime.Add(DateTime.Parse(dr["TIMESTAMP"].ToString()));
                                    kwh.Add(Convert.ToDouble(dr["KWH_CAL"]));
                                    kvah.Add(Convert.ToDouble(dr["KVAH_CAL"]));
                                    kvarh.Add(Convert.ToDouble(dr["KVARH_CAL"]));
                                }//foreach

                                // Create the Bar Graph
                                this.grhHistoricEnergy.updateHistoricBarCurves(datetime, kwh, kvah, kvarh, "%h");

                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch
                            break;

                        case 60:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlENERGYLOG60HOUR);

                                //Data Containers
                                List<DateTime> datetime = new List<DateTime>();
                                List<double> kwh = new List<double>();
                                List<double> kvah = new List<double>();
                                List<double> kvarh = new List<double>();

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    datetime.Add(DateTime.Parse(dr["TIMESTAMP"].ToString()));
                                    kwh.Add(Convert.ToDouble(dr["KWH_CAL"]));
                                    kvah.Add(Convert.ToDouble(dr["KVAH_CAL"]));
                                    kvarh.Add(Convert.ToDouble(dr["KVARH_CAL"]));
                                }//foreach

                                // Create the Bar Graph
                                this.grhHistoricEnergy.updateHistoricBarCurves(datetime, kwh, kvah, kvarh, "%h");

                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch
                            break;
                    }//switch
                    break;

                case "E_DAY"    :

                    // Set Default Graph Options
                    this.grhHistoricEnergy.setGraphPane(String.Format("Historic Energy Month Graph@{0}", strMeter), String.Format("For Month:{0}/{1}", dateTimePickerHistoricTo.Value.Month, dateTimePickerHistoricTo.Value.Year), "Energy(KWh/KVAh/KVARh)");
                    this.grhHistoricEnergy.clearHistoricBarCurves();
                    this.grhHistoricEnergy.assignGraph(grpBoxHistoricGraphEnergy);
                    
                    switch (MeterQueryTime)
                    {
                        case 15:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlENERGYLOG15DAY);

                                //Data Containers
                                List<DateTime> datetime = new List<DateTime>();
                                List<double> kwh = new List<double>();
                                List<double> kvah = new List<double>();
                                List<double> kvarh = new List<double>();

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    datetime.Add(DateTime.Parse(dr["TIMESTAMP"].ToString()));
                                    kwh.Add(Convert.ToDouble(dr["KWH_CAL"]));
                                    kvah.Add(Convert.ToDouble(dr["KVAH_CAL"]));
                                    kvarh.Add(Convert.ToDouble(dr["KVARH_CAL"]));
                                }//foreach

                                // Create the Bar Graph
                                this.grhHistoricEnergy.updateHistoricBarCurves(datetime, kwh, kvah, kvarh, "%d");                                

                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch
                            break;

                        case 30:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlENERGYLOG30DAY);

                                //Data Containers
                                List<DateTime> datetime = new List<DateTime>();
                                List<double> kwh = new List<double>();
                                List<double> kvah = new List<double>();
                                List<double> kvarh = new List<double>();

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    datetime.Add(DateTime.Parse(dr["TIMESTAMP"].ToString()));
                                    kwh.Add(Convert.ToDouble(dr["KWH_CAL"]));
                                    kvah.Add(Convert.ToDouble(dr["KVAH_CAL"]));
                                    kvarh.Add(Convert.ToDouble(dr["KVARH_CAL"]));
                                }//foreach

                                // Create the Bar Graph
                                this.grhHistoricEnergy.updateHistoricBarCurves(datetime, kwh, kvah, kvarh, "%d");

                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch
                            break;

                        case 60:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlENERGYLOG60DAY);

                                //Data Containers
                                List<DateTime> datetime = new List<DateTime>();
                                List<double> kwh = new List<double>();
                                List<double> kvah = new List<double>();
                                List<double> kvarh = new List<double>();

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    datetime.Add(DateTime.Parse(dr["TIMESTAMP"].ToString()));
                                    kwh.Add(Convert.ToDouble(dr["KWH_CAL"]));
                                    kvah.Add(Convert.ToDouble(dr["KVAH_CAL"]));
                                    kvarh.Add(Convert.ToDouble(dr["KVARH_CAL"]));
                                }//foreach

                                // Create the Bar Graph
                                this.grhHistoricEnergy.updateHistoricBarCurves(datetime, kwh, kvah, kvarh, "%d");

                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch
                            break;
                    }//switch
                    break;

                case "E_MONTH"  :

                    // Set Default Graph Options
                    this.grhHistoricEnergy.setGraphPane(String.Format("Historic Energy Year Graph@{0}", strMeter), String.Format("For Year:{0}", dateTimePickerHistoricTo.Value.Year), "Energy(KWh/KVAh/KVARh)");
                    this.grhHistoricEnergy.clearHistoricBarCurves();
                    this.grhHistoricEnergy.assignGraph(grpBoxHistoricGraphEnergy);

                    switch (MeterQueryTime)
                    {
                        case 15:
                            try
                            {                                                                
                                dtDATALOG = db.GetDataTable(sqlENERGYLOG15MONTH);

                                //Data Containers
                                List<DateTime> datetime = new List<DateTime>();
                                List<double> kwh = new List<double>();
                                List<double> kvah = new List<double>();
                                List<double> kvarh = new List<double>();

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    datetime.Add(DateTime.Parse(dr["TIMESTAMP"].ToString()));
                                    kwh.Add(Convert.ToDouble(dr["KWH_CAL"]));
                                    kvah.Add(Convert.ToDouble(dr["KVAH_CAL"]));
                                    kvarh.Add(Convert.ToDouble(dr["KVARH_CAL"]));
                                }//foreach

                                // Create the Bar Graph
                                this.grhHistoricEnergy.updateHistoricBarCurves(datetime, kwh, kvah, kvarh, "%m");

                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch
                            break;

                        case 30:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlENERGYLOG30MONTH);

                                //Data Containers
                                List<DateTime> datetime = new List<DateTime>();
                                List<double> kwh = new List<double>();
                                List<double> kvah = new List<double>();
                                List<double> kvarh = new List<double>();

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    datetime.Add(DateTime.Parse(dr["TIMESTAMP"].ToString()));
                                    kwh.Add(Convert.ToDouble(dr["KWH_CAL"]));
                                    kvah.Add(Convert.ToDouble(dr["KVAH_CAL"]));
                                    kvarh.Add(Convert.ToDouble(dr["KVARH_CAL"]));
                                }//foreach

                                // Create the Bar Graph
                                this.grhHistoricEnergy.updateHistoricBarCurves(datetime, kwh, kvah, kvarh, "%m");

                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch
                            break;

                        case 60:
                            try
                            {
                                dtDATALOG = db.GetDataTable(sqlENERGYLOG60MONTH);

                                //Data Containers
                                List<DateTime> datetime = new List<DateTime>();
                                List<double> kwh = new List<double>();
                                List<double> kvah = new List<double>();
                                List<double> kvarh = new List<double>();

                                foreach (DataRow dr in dtDATALOG.Rows)
                                {
                                    datetime.Add(DateTime.Parse(dr["TIMESTAMP"].ToString()));
                                    kwh.Add(Convert.ToDouble(dr["KWH_CAL"]));
                                    kvah.Add(Convert.ToDouble(dr["KVAH_CAL"]));
                                    kvarh.Add(Convert.ToDouble(dr["KVARH_CAL"]));
                                }//foreach

                                // Create the Bar Graph
                                this.grhHistoricEnergy.updateHistoricBarCurves(datetime, kwh, kvah, kvarh, "%m");

                            }//try
                            catch (Exception Ex)
                            {
                                MessageBox.Show(Ex.Message);
                            }//catch
                            break;
                    }//switch
                    break;
            } //switch
        } //updateHistoricGraph

        private void cboHistoricSelection_Click(object sender, EventArgs e)
        {
            if (strHistoricMeterSelected != "")
            {
                updateHistoricGraph(cboHistoricSelection.Text, strHistoricMeterSelected, dateTimePickerHistoricFrom.Value, dateTimePickerHistoricTo.Value);
            }
            else
            {
                MessageBox.Show("Make Sure Site/Meter Selected", "Historic Selection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        } //cboHistoricSelection_Click

        private void cboHistoricSelection_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (strHistoricMeterSelected != "")
            {
                updateHistoricGraph(cboHistoricSelection.Text, strHistoricMeterSelected, dateTimePickerHistoricFrom.Value, dateTimePickerHistoricTo.Value);
            }
            else
            {
                MessageBox.Show("Make Sure Site/Meter Selected", "Historic Selection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        } //cboHistoricSelection_SelectedIndexChanged

        private void dateTimePickerHistoricFrom_ValueChanged(object sender, EventArgs e)
        {
            if (strHistoricMeterSelected != "")
            {
                // Check to make sure From/To values match
                if (dateTimePickerHistoricFrom.Value >= dateTimePickerHistoricTo.Value)
                {
                    dateTimePickerHistoricFrom.Value = dateTimePickerHistoricTo.Value.AddDays(-1);
                }//if

                // Update Graph
                updateHistoricGraph(cboHistoricSelection.Text, strHistoricMeterSelected, dateTimePickerHistoricFrom.Value, dateTimePickerHistoricTo.Value);
            }
            else
            {
                MessageBox.Show("Make Sure Site/Meter Selected", "Historic Selection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        } //dateTimePickerHistoricFrom_ValueChanged

        private void dateTimePickerHistoricTo_ValueChanged(object sender, EventArgs e)
        {        

            if (strHistoricMeterSelected != "")
            {
                // Check to make sure From/To values match
                if (dateTimePickerHistoricFrom.Value >= dateTimePickerHistoricTo.Value)
                {
                    dateTimePickerHistoricFrom.Value = dateTimePickerHistoricTo.Value.AddDays(-1);
                }//if

                updateHistoricGraph(cboHistoricSelection.Text, strHistoricMeterSelected, dateTimePickerHistoricFrom.Value, dateTimePickerHistoricTo.Value);
            }
            else
            {
                MessageBox.Show("Make Sure Site/Meter Selected", "Historic Selection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }//dateTimePickerHistoricTo_ValueChanged

    } //class
} //namespace
